objective c - 从Web下载图像并使用它在图像视图中显示的有效方法

时间:2014-02-10 12:32:01

标签: ios iphone objective-c uiimageview

在我的应用程序中可以说ViewA和ViewB有2个视图

ViewA中有

按钮供用户选择选项。如果他推送其中一个,我会通过网络服务从网上提取一些图像,并将它们下载到用户的机器上,我也会把它们的路径放到一个数组中。

然后在ViewB中我想从该数组中获取图像并在图像视图中显示它们

这是我下载图片的方式

-(void)startDownload
{
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:@"http://xxxx.com/Tulips.jpg"];
[arr addObject:@"http://xxxx.com/Koala.jpg"];
[arr addObject:@"http://xxxx.com/Penguins.jpg"];
for (int i=0; i<[arr count]; i++)   //download array have url links
{
    NSURL *URL = [NSURL URLWithString:[arr objectAtIndex:i]];
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:URL];
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue  completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if([data length] > 0 && [[NSString stringWithFormat:@"%@",error] isEqualToString:@"(null)"])
         {
             //make your image here from data.
             UIImage *imag = [[UIImage alloc] initWithData:[NSData dataWithData:data]];
             NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
             NSString *docDir = [array objectAtIndex:0];
             NSString *imgstr=[NSString stringWithFormat:@"%d",i];
             NSString *pngfilepath = [NSString stringWithFormat:@"%@sample%@.jpg",docDir,imgstr];
             NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(imag)];
             [data1 writeToFile:pngfilepath atomically:YES];


             img = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:pngfilepath]];

             NSLog(@"file is written");

         }
         else if ([data length] == 0 && [[NSString stringWithFormat:@"%@",error] isEqualToString:@"(null)"])
         {
             NSLog(@"No Data!");
         }
         else if (![[NSString stringWithFormat:@"%@",error] isEqualToString:@"(null)"]){
             NSLog(@"Error = %@", error);
         }
     }];

}



}

当我运行应用程序时,我看到该文件已写入日志正在运行,所以我认为下载图像是成功但我无法在imageview中显示图像

你可以考虑在商店里测试app,以便清楚地理解我的问题。测试首先下载问题的图像然后在另一个视图中使用它们。这就是我想要的。

如果我的下载代码是正确的,我该如何显示它们?

3 个答案:

答案 0 :(得分:2)

此代码允许您从网上下载图像,并且不需要将图像保存在文档目录中:

 NSMutableArray *arry = [[NSMutableArray alloc] init];
 [arry addObject:@"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRr0WK-Q2t4Xxr1b6Kl7-lXdVEIh_Hj3HiDXk--Qg_0UAY0Y96P6w"];
 [arry addObject:@"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRr0WK-Q2t4Xxr1b6Kl7-lXdVEIh_Hj3HiDXk--Qg_0UAY0Y96P6w"];
 [arry addObject:@"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRr0WK-Q2t4Xxr1b6Kl7-lXdVEIh_Hj3HiDXk--Qg_0UAY0Y96P6w"];

 for (int i=0; i<[arry count]; i++)   //download array have url links
 {
    NSString *string=[arry objectAtIndex:i];
    NSURL *url=[NSURL URLWithString:string];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

        [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
         {
             UIImage *imagemain=[UIImage imageWithData:data];
             //         CGSize size=imagemain.size;
          //  UIImage *compimage=[appdel resizeImage:imagemain resizeSize:CGSizeMake(45,45)];
    //
    //         Cell.imgProfile.image=compimage;
    //         //         CGSize size1=compimage.size;
             imageView.image=imagemain;
         }];

}

答案 1 :(得分:1)

您是否在主线程上更新UIImageView,无法从后台线程更新UI元素。试试

        dispatch_sync(dispatch_get_main_queue(),
        ^{
            imageView.image = yourImage;
        });

答案 2 :(得分:1)

您必须使用SDWebImage来缓存图片。意味着网址不会一次又一次地被击中。

#import "UIImageView+WebCache.h"

-(void)startDownload
{
  NSMutableArray *arr = [[NSMutableArray alloc] init];
  [arr addObject:@"http://xxxx.com/Tulips.jpg"];
  [arr addObject:@"http://xxxx.com/Koala.jpg"];
  [arr addObject:@"http://xxxx.com/Penguins.jpg"];
     for (int i=0; i<[arry count]; i++)   //download array have url links
     {
        NSString *string=[arry objectAtIndex:i];
        NSURL *url=[NSURL URLWithString:string];

          SDWebImageManager *manager = [SDWebImageManager sharedManager];
          [manager downloadWithURL:url progress:^(NSUInteger receivedSize, long long expectedSize)
            {
                 // progression tracking code
             }completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
                {
                    if (image)
                           {
                  // here you can setup imageView frames and set the image on imageView
                          imageView.image=image;
                            }
                  }];
                        }
    }

   }