0

I just read about NSURLSession and I used it to download images from a url.Here i.e. the method that I wrote :

    -(void)startDownloadingWithURLString:(NSString*)urlString andDisplayOn:(UIImageView*)imageView{

            NSURL *url = [NSURL URLWithString:urlString];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];

            NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
            NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:configuration];
            NSLog(@"%@",dataResponse);
            NSURLSessionDownloadTask *task = [urlSession downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                  UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];

                  dispatch_async(dispatch_get_main_queue(), ^{

                  imageView.image = image;
                 });
           }];
           [task resume];
      }

Now the problem is that I am calling this method inside "cellForItemAtIndexPath:".So overtime I scroll,this method gets called again and again for each cell(reusability concept).Now,as the download process is asynchronous,I can't know when the downloading is complete.

So what should I do to avoid this problem?I just want to download images once.

Rohit Pradhan
  • 3,867
  • 1
  • 21
  • 29
Reckoner
  • 1,041
  • 2
  • 13
  • 29

1 Answers1

0

There are third party libraries available to solve your purpose. I prefer using SDWebImage for the same. It worked like a charm for me.

Just import

#import<SDWebImage/UIImageView+WebCache.h>

and you can use the method to load the web image

 sd_setImageWithURL: 

It does the same work for you without hustle. Refer this link https://github.com/rs/SDWebImage Hope it helps. Hapy Coding..

luckyShubhra
  • 2,731
  • 1
  • 12
  • 19