我从链接下载图像并将其添加到NSMutableArray
中。然后将其用作细胞图像。我从一个链接中获得一个图书列表,并过滤表中的内容,然后我有一个单独的链接,其中有相应的图像。带有优惠的第一个链接有一个图像路径,该路径被附加到一个链接以查找相应的图像。我正在使用grand-central dispatch来加载表视图中的图像。然而,这些图像并不总是与正确的书相对应。
这是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;
我是一个相当新的,所以我很抱歉任何糟糕的编码。
您可以使用AFNetworking,它异步下载数据和图像,而且非常易于使用。
编辑:如何下载图像的示例
NSURL *URL = [NSString stringWithFormat:@"http://website/getBookImage.app?path=%@",[b.imgPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
imageSection.image = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];