How can i load images to a UICollectionview
asynchronously?
Inside following method?
- (PSTCollectionViewCell *)collectionView:(PSTCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
bookImage = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", docPath, [[preview objectAtIndex:indexPath.row] lastPathComponent]]];
[[cell grid_image] setImage:bookImage];
}
In viewdidload() i am using following asynch call to load images to "preview "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];
});
Please help me..Now its taking too much time for loading...
Use Lazy Load File for your requirement.
LazyLoad.h
LazyLoad.m
Use them like this
Download Demo Here
Trying to answer your main question "How can i load images to a
UICollectionview
asynchronously?"I would suggest solution offered by "Natasha Murashev" here, which worked nicely for me and it's simple.
If here
imgURL = [allImage objectAtIndex:k];
inallImage
property you keep array of URLs, then update yourcollectionView:cellForItemAtIndexPath:
method like this:And add method
downloadImageWithURL:completionBlock:
to your class, which will load images asynchronously and update cells in CollectionView automatically when images are successfully downloaded.I see you try to preload images before view appears so maybe my solution isn't what you what, but from your question it's hard to say. Any how, you can achieve what you want with this as well.
Swift 2.2 Solution in Swift.
Usage sample:
This code creates serial queue:
therefore each task IN QUEUE is performed in the same thread successive. Therefore your single work thread is sustained by sleep for each task of loading that slow down all process of loading.
Use asynchronous CONCURRENT queue by using something like that: