简体   繁体   中英

Preload Asynchronous Image to show in UIimageview offline

I write app to use picture from url to show in UIimageview but I run in iPhone imageview do not show picture this is my code

 __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];   
}

u are set image before it download set image in block as show below

[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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM