预加载异步图像以在UIimageview中脱机显示

时间:2016-04-18 04:53:14

标签: ios objective-c uiimageview

我写的应用程序使用url中的图片显示在UIimageview但我在iPhone中运行imageview不显示图片这是我的代码

 __block UIImage *pic1,*pic2,*pic3;
UIImageView *p1,*p2,*p3;
NSString *strImgURLAsString = mylink;
NSString *strImgURLAsString2 = mylink2;

[strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *imgURL = [NSURL URLWithString:strImgURLAsString];

[strImgURLAsString2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *imgURL = [NSURL URLWithString:strImgURLAsString];
 NSURL *imgURL2 = [NSURL URLWithString:strImgURLAsString2];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"downloaded");
        pic1 = [[UIImage alloc] initWithData:data];     
}];
 [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSLog(@"downloaded");
            pic2 = [[UIImage alloc] initWithData:data];     
    }];
 [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"downloaded");
        pic1 = [[UIImage alloc] initWithData:data];     
}];

if([name isEqualToString:@"des1"])// it is restoration of viewcontroller{
    [p1 setImage:pic1];   
}
else if ([name isEqualToString:@"des2"])// it is restoration of viewcontroller{
 [p1 setImage:pic2];   
}

1 个答案:

答案 0 :(得分:-1)

u在下载之前设置图像 在块中设置图像如下所示

[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSLog(@"downloaded");
    dispatch_async(dispatch_get_main_queue(), ^{
    pic1 = [[UIImage alloc] initWithData:data];     
if([name isEqualToString:@"des1"]){
[p1 setImage:pic1];   
        });

}

}];

    dispatch_async(dispatch_get_main_queue(), ^{        }) use for load image on main thread because u download image asynchronous