[[Server sharedInstance] getItems:^(id response, NSError *error) {
[self hideActivityIndicator];
if (error) {
[self showErrorDialogWithMessage:error.localizedDescription];
} else {
self.items = ((NSArray<Item*>*)response).data;
self.itemsHeights = [[NSMutableArray alloc] initWithCapacity:self.items.count];
for (int i = 0; i < self.items.count; i++) {
[self.itemsHeights addObject:[NSNumber numberWithInt:160]];
}
if (self.items.count != 0) {
[self noResultsViewHidden:YES];
}
[self.tableView reloadData];
}
}];
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Product* item = item = self.items[indexPath.row];
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
// Customize cell
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:item.picture]];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
__block UIImageView* imageViewRef = cell.itemImageView;
__block NSIndexPath *blockIndexPath = indexPath;
[cell.itemImageView cancelImageDownloadTask];
AFImageDownloader* downloader = [UIImageView sharedImageDownloader];
UIImage *cachedImage = [downloader.imageCache imageforRequest:request withAdditionalIdentifier:nil];
if (cachedImage) {
cell.productImageView.image = cachedImage;
long height = cell.frame.size.width * cachedImage.size.height / cachedImage.size.width;
[self.itemsHeights setObject:[NSNumber numberWithLong:height] atIndexedSubscript:blockIndexPath.row];
} else {
[cell.productImageView setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
long height = cell.frame.size.width * image.size.height / image.size.width;
[self.itemsHeights setObject:[NSNumber numberWithLong:height] atIndexedSubscript:blockIndexPath.row];
float scale = image.size.width / self.tableView.frame.size.width;
UIImage* scaledImage = [UIImage imageWithCGImage:image.CGImage scale:image.scale * scale orientation:image.imageOrientation];
dispatch_async(dispatch_get_main_queue(), ^{
imageViewRef.image = scaledImage;
if ([self.tableView.indexPathsForVisibleRows containsObject:blockIndexPath]) {
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
}
});
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
imageViewRef.image = nil;
}];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
return self.itemsHeights[indexPath.row].longValue;
}
No hay comentarios:
Publicar un comentario