Taking time to load the image from URL to UIImageview

后端 未结 3 996
死守一世寂寞
死守一世寂寞 2020-12-20 05:43

I am using this code for displaying the image from URL to UIImageview

UIImageView *myview=[[UIImageView alloc]init];

myview.frame = CGRectMake(50, 50, 320,         


        
相关标签:
3条回答
  • 2020-12-20 06:30
    Use Dispatch queue to load image from URL.
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
    
      });
    
    Or add a placeholder image till your image gets load from URL.
    
    0 讨论(0)
  • 2020-12-20 06:36

    Instead of dispatch_async, Use SDWebImage for caching the images.

    This is best I have seen...

    The problem of dispatch_async is that if you lost focus from image, it will load again. However SDWebImage, Caches the image and it wont reload again.

    0 讨论(0)
  • 2020-12-20 06:47

    The answers given to me on my own question Understanding the behaviour of [NSData dataWithContentsOfURL:URL] inside the GCD block does makes sense.So be sure that if you use [NSData dataWithContentsOfURL:URL] inside the GCD(as many developers do these days) is not a great idea to download the files/images.So i am leaning towards the below approach(you can either use NSOperationQueue).

    Load your images using [NSURLConnection sendAsynchronousRequest:queue:completionHandler: then use NSCache to prevent downloading the same image again and again.

    As suggested by many developers go for SDWebimage and it does include the above strategy to download the images files .You can load as many images you want and the same URL won't be downloaded several times as per the author of the code

    EDIT:

    Example on [NSURLConnection sendAsynchronousRequest:queue:completionHandler:

    NSURL *url = [NSURL URLWithString:@"your_URL"];
    NSURLRequest *myUrlRequest = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:myUrlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
    
        if ([data length] > 0 && error == nil)
            //doSomething With The data
    
        else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
            //time out error
    
        else if (error != nil)
            //download error
    }];
    
    0 讨论(0)
提交回复
热议问题