2013-08-03 19 views
6

UICollectionviewに画像を非同期で読み込むにはどうすればよいですか? 以下の方法はありますか? のviewDidLoad()イメージをUICollectionViewに非同期で読み込みますか?

- (PSTCollectionViewCell *)collectionView:(PSTCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 

bookImage = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", docPath, [[preview objectAtIndex:indexPath.row] lastPathComponent]]]; 
[[cell grid_image] setImage:bookImage]; 

} 

私はそののロードのためにあまりにも多くの時間を取ってme..Now助けてください "プレビュー" NSMutablearray

dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", NULL); 

dispatch_async(imageLoadQueue, ^{ 
    //Wait for 5 seconds... 
    usleep(1000000); 
    docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 


    for(int k=0; k <[allImage count] ;k++){ 


     imgURL = [allImage objectAtIndex:k]; 
     [imagePreview addObject:imgURL]; 
     imgData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]]; 


     [imgData writeToFile:[NSString stringWithFormat:@"%@/%@", docPath, [allImage lastPathComponent]] atomically:YES]; 

    } 

    [[self collectionView] reloadData]; 


}); 

に画像をロードするには、次の非同期呼び出しを使用しています...

+0

特に時間がかかりすぎて何?画像のサイズは? – Wain

+0

これを[[self collectionView] reloadData]にする必要があります。メインスレッド。それは答えではありません。コメントだけです。 – stosha

+0

を使用するEGOImageView: https://github.com/enormego/EGOImageLoading –

答えて

0

このコードは、シリアルキューを作成します。

dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", NULL); 

したがって、各タスクIN QUEUEは同じスレッドで連続して実行されます。したがって、負荷の各タスクがスリープ状態になると、すべての処理が遅くなります。そのようなものを使用して

使用非同期CONCURRENTキュー:あなたの条件のため

dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", DISPATCH_QUEUE_CONCURRENT); 
+0

したがって、メインスレッドでreloadDataを使用してください。そのようなdispatch_async(dispatch_get_main_queue()、^ {// reloadData}); – user2595925

+0

私はPSTCollectionViewをディスエイブルするために新しいレイジーローディングメソッドを使うべきだと思います – Navi

-1

使用レイジー・ロード・ファイル。

LazyLoad.h
LazyLoad.m

あなたの主な質問に答えるためにしようと、この

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 

    [cell addSubview:[self addViewWithURL:@"http://openwalls.com/image/399/explosion_of_colors_1920x1200.jpg" NFrame:CGRectMake(0, 0, 50, 50)]]; 

    cell.backgroundColor=[UIColor blueColor]; 
    return cell; 
} 

-(UIView*)addViewWithURL:(NSString*)urlStr NFrame:(CGRect)rect 
{ 
    LazyLoad *lazyLoading; 

    lazyLoading = [[LazyLoad alloc] init]; 
    [lazyLoading setBackgroundColor:[UIColor grayColor]]; 
    [lazyLoading setFrame:rect]; 

    [lazyLoading loadImageFromURL:[NSURL URLWithString:urlStr]]; 
    return lazyLoading; 
} 

Download Demo Here

+0

UICollectionview cell.imageview.imageで画像を表示するにはどうすればいいですか? – Navi

+0

cellView.imageプロパティはtableView.MyCodeのCollectionViewにのみ存在しますイメージを非同期でロードし、collectionViewセルにサブビューとして追加します。 – Warewolf

+0

myCodeをhttp://stackoverflow.com/a/17856406/1305001で追加するか、代わりにカスタムセルを使用する必要があります – Warewolf

8

のようにそれらを使用して "私は非同期UICollectionviewにイメージをロードできますか?"

私は私のためにうまく働いていた「ナターシャMurashevhere、によって提供される解決策を示唆しているであろうし、それは簡単です。

- (PSTCollectionViewCell *)collectionView:(PSTCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSURL *url = [NSURL URLWithString:[allImage objectAtIndex:indexPath]]; 

    [self downloadImageWithURL:url completionBlock:^(BOOL succeeded, NSData *data) { 
     if (succeeded) { 
      cell.grid_image.image = [[UIImage alloc] initWithData:data]; 
     } 
    }]; 
} 

を、自動的にCollectionViewで非同期に画像や更新細胞をロードする、あなたのクラスにメソッドdownloadImageWithURL:completionBlock:を追加します。

あなたはURLの配列を保つimgURL = [allImage objectAtIndex:k];プロパティallImageにここにいる場合、このようなあなたのcollectionView:cellForItemAtIndexPath:方法を更新画像が正常にダウンロードされたとき。

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock 
{ 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
     if (!error) { 
      completionBlock(YES, data); 
     } else { 
      completionBlock(NO, nil); 
     } 
    }]; 
} 

私はあなたのビューはので、多分私の解決策は、あなたがどのようなものではなく、あなたの質問から、それは言うのは難しいのです表示される前に、画像をプリロードしてみてください参照してください。どのように、あなたはこれでもあなたが望むものを達成することができます。

スウィフト2.2 スウィフトのソリューション。

public typealias ImageFetchCompletionClosure = (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void 

extension String { 
    func fetchImage(completionHandler: (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void) { 
     if let imageURL = NSURL(string: self) { 
      NSURLSession.sharedSession().dataTaskWithURL(imageURL) { data, response, error in 
       guard 
        let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200, 
        let mimeType = response?.MIMEType where mimeType.hasPrefix("image"), 
        let data = data where error == nil, 
        let image = UIImage(data: data) 
        else { 
         if error != nil { 
          completionHandler(image: nil, error: error, imageURL: imageURL) 
         } 
         return 
       } 
       dispatch_sync(dispatch_get_main_queue()) {() -> Void in 
        completionHandler(image: image, error: nil, imageURL: imageURL) 
       } 
      }.resume() 
     } 
    } 
} 

使用サンプル:

"url_string".fetchImage { (image, error, imageURL) in 
     // handle different results, either image was downloaded or error received 
    } 
+0

セルを再利用することができず、セルを他のイメージデータで効率的に上書きできますか?あなたのサンプルではセルも定義されていません;) – Andy

+0

これは主に、画像を非同期的に読み込む方法であり、セルで効率的に動作する方法ではありません。 – Jonauz