2013-08-03 36 views
6

Tôi làm cách nào để tải hình ảnh lên UICollectionview không đồng bộ? Bên trong phương pháp sau đây?Tải hình ảnh về UICollectionView Không đồng bộ?

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

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

} 

Trong viewDidLoad() tôi đang sử dụng sau đây gọi asynch để tải hình ảnh để "xem trước" 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]; 


}); 

Xin giúp me..Now dùng nó quá nhiều thời gian để tải ...

+0

gì là dùng quá lâu đặc biệt? Và hình ảnh là kích cỡ nào? – Wain

+0

bạn nên thực hiện [[self collectionView] reloadData] này [[self collectionView] reloadData]; trong chủ đề chính. Nó không phải là một câu trả lời. Đó chỉ là bình luận. – stosha

+0

sử dụng EGOImageView: https://github.com/enormego/EGOImageLoading –

Trả lời

0

mã này tạo ra hàng đợi nối tiếp:

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

do đó mỗi nhiệm vụ IN QUEUE được thực hiện trong cùng một chuỗi liên tiếp. Do đó, chuỗi công việc duy nhất của bạn được duy trì bằng giấc ngủ cho mỗi tác vụ tải xuống làm chậm quá trình tải.

Sử dụng đồng bộ hàng đợi đồng thời bằng cách sử dụng một cái gì đó như thế:

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

Và sử dụng reloadData trên chuỗi chính. Giống như dispatch_async (dispatch_get_main_queue(),^{// reloadData}); – user2595925

+0

tôi nghĩ rằng tôi nên sử dụng một phương pháp tải lười mới để disaplay cho PSTCollectionView của tôi – Navi

-1

Sử dụng Lazy Load File cho yêu cầu của bạn.

LazyLoad.h
LazyLoad.m

Sử dụng chúng như thế này

- (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

Làm thế nào tôi có thể hiển thị hình ảnh trong UICollectionview cell.imageview.image, thats câu hỏi của tôi – Navi

+0

thuộc tính cell.imageview.image không tồn tại trong CollectionView chỉ trong tableView.MyCode sẽ tải hình ảnh không đồng bộ và thêm dưới dạng xem con trong ô sưu tậpXem. – Warewolf

+0

thêm myCode với http://stackoverflow.com/a/17856406/1305001 hoặc u cần sử dụng ô tùy chỉnh thay vì – Warewolf

8

Đang cố gắng để trả lời câu hỏi chính của bạn "Làm thế nào tôi có thể tải hình ảnh đến một UICollectionview không đồng bộ?"

Tôi sẽ đề xuất giải pháp được cung cấp bởi "Natasha Murashev" here, hoạt động tốt cho tôi và thật đơn giản.

Nếu đây imgURL = [allImage objectAtIndex:k]; trong allImage tài sản mà bạn giữ mảng các URL, sau đó cập nhật phương thức collectionView:cellForItemAtIndexPath: của bạn như thế này:

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

Và thêm phương pháp downloadImageWithURL:completionBlock: đến lớp học của bạn, mà sẽ tải hình ảnh không đồng bộ và các tế bào cập nhật trong CollectionView tự động khi hình ảnh được tải xuống thành công.

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

tôi thấy bạn cố gắng để tải trước hình ảnh trước khi xem xuất hiện như vậy có lẽ giải pháp của tôi không phải là những gì bạn thấy những gì, nhưng từ câu hỏi của bạn thật khó để nói. Làm thế nào, bạn có thể đạt được những gì bạn muốn với điều này là tốt.

Swift 2.2 Giải pháp trong Swift.

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() 
     } 
    } 
} 

mẫu Cách sử dụng:

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

Không phải là các tế bào có thể được tái sử dụng và bạn ghi đè lên một cách hiệu quả các tế bào với một số dữ liệu hình ảnh khác? Ngoài ra tế bào là không xác định trong mẫu của bạn;) – Andy

+0

Nó chủ yếu có nghĩa là để trả lời làm thế nào để tải hình ảnh không đồng bộ, không phải làm thế nào để làm việc hiệu quả với các tế bào :) Mặc dù, cảm ơn cho chỉ nó ra. – Jonauz

Các vấn đề liên quan