2016-01-25 31 views
0

我剛剛看了一下NSURLSession,我用它來從我寫了url.Here即方法下載圖片:NSURLSession與UICollectionView

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

現在的問題是,我打電話裏面"cellForItemAtIndexPath:"此方法。因此,我加班滾動,這個方法一次又一次地被調用(可重用性概念)。現在,由於下載過程是異步的,我無法知道下載何時完成。

那麼我該怎麼做才能避免這個問題?我只想下載一次圖像。

+0

使用現有的選項,如SDWebImage – Wain

+0

正如我剛剛開始瞭解這些概念,我想有一個解決方案,而不使用任何現有的第三方類。我希望有一個更合乎邏輯的解決方案。 – Reckoner

+0

http://stackoverflow.com/questions/11511548/best-way-to-cache-images-on-ios-app引用此鏈接。它會幫助你。 –

回答

0

有第三方庫可用於解決您的目的。我更喜歡使用SDWebImage。它對我來說就像一個魅力。

只需導入

#import<SDWebImage/UIImageView+WebCache.h> 

,您可以使用該方法來加載Web圖像

sd_setImageWithURL: 

它做同樣的工作,你沒有喧囂。 請參閱此鏈接https://github.com/rs/SDWebImage 希望它有幫助。 Hapy編碼..