I download images from links and add it to an NSMutableArray
. This is then to be used as the cell image. I get a list of books from one link and filter the content of the table, then I have a separate link that has their corresponding images. The first link with the offers has an image path that is appended to a link to find the corresponding images. I am using grand central dispatch to load the images in the tableview. However the images do not always correspond to the correct book.
This is the code in question for cellForRowAtIndexPath
:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * url = [NSString stringWithFormat:@"http://website/getBookImage.app?path=%@",[b.imgPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL * imageURL = [NSURL URLWithString:url];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * newImage = [UIImage imageWithData:imageData];
UIImage * noPic = [UIImage imageNamed:@"noPic.jpg"];
//resize the images
CGRect rect = CGRectMake(0,0,111,115);
UIGraphicsBeginImageContext( rect.size );
[newImage drawInRect:rect];
UIImage *picture1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIGraphicsBeginImageContext( rect.size );
[noPic drawInRect:rect];
UIImage * pic2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData2 = UIImagePNGRepresentation(picture1);
NSData * noPicData = UIImagePNGRepresentation(pic2);
//if image is
if (imageData.length == 0 ) {
[self.merchantImage addObject:noPicData];
}else{
[self.merchantImage addObject:imageData2];
}
NSLog(@"image data %@",imageData);
//call to main thread to tell it that its done
//set cells
dispatch_async(dispatch_get_main_queue(), ^{
//set cells here
//3.set the image cell
imageSection.image = [UIImage imageWithData:[self.bookImage objectAtIndex:i];
//tell cell to redraw
i++;
[cell setNeedsLayout];
});
// }
});
return cell;
I am fairly new so I am sorry for any bad coding.