here is the code for my collectionview it is showing records but loading really please tell me how can i implement lazy loading on this i also have a placeholder pic in my project
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MJCell" forIndexPath:indexPath];
// Setup image name
NSString *url = [[rssOutputData objectAtIndex:indexPath.row]xmllink];
UIImage *img = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
img = [[UIImage alloc] initWithData:data];
cell.MJImageView.image = img;
return cell;
}
right now it is working but very very slow.
It's pretty easy to do lazy loading using GCD.
// Create a queue for the operations
dispatch_queue_t queue = dispatch_queue_create("photoList", NULL);
// Start getting the data in the background
dispatch_async(queue, ^{
NSData* photoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:object.photoURL]];
UIImage* image = [UIImage imageWithData:photoData];
// Once we get the data, update the UI on the main thread
dispatch_sync(dispatch_get_main_queue(), ^{
cell.photoImageView.image = image;
});
});
The easiest way to implement that is use SDWebImage library, it does right what you need. There is UIImageView
category that will allow you to modify code for that:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MJCell" forIndexPath:indexPath];
// Setup image name
NSString *url = [[rssOutputData objectAtIndex:indexPath.row]xmllink];
[cell.MJImageView sd_setImageWithURL:[NSURL URLWithString:url]];
return cell;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With