我在我当前的一个项目中下载图像时使用此代码,但它不能与AFNetworking 2.0一起使用。我试过通过AFImageResponseSerializer,但我找不到合适的代码。
[cell.posterImage setImageWithURLRequest:urlRequest placeholderImage:[UIImage imageNamed:@"placeholder.png"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
cell.posterImage.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Request failed with error: %@", error);
}];
有关AFNetworking 2.0中使用的新代码的任何建议吗?谢谢!
答案 0 :(得分:4)
我使用此代码使其工作:
AFHTTPRequestOperation *posterOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
posterOperation.responseSerializer = [AFImageResponseSerializer serializer];
[posterOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Response: %@", responseObject);
_posterImageView.image = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Image request failed with error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:posterOperation];
[posterOperation start];
但是我使用它来解决占位符图像的另一个问题。有什么想法吗?
答案 1 :(得分:3)
您正在寻找UIImageView (AFNetworking)
category。
#import "UIImageView+AFNetworking.h"
//...
[cell.posterImage setImageWithURLRequest:urlRequest placeholderImage:[UIImage imageNamed:@"placeholder.png"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
cell.posterImage.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Request failed with error: %@", error);
}];
cell.posterImage
必须是UIImageView
,而不是UIImage
。
答案 2 :(得分:2)
使用更新的AFNetworking 2.0
(如果您的文件仅供下载使用,则无法通过简单的网址访问):
NSString * methodURL = @"http://www.yourserver.com/pathToImageDownloadMethod";
NSInteger someIDYouHaveOfAnImage = 13;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFImageResponseSerializer serializer];
NSDictionary * parameterDictionary = @{@"Parameter" : [NSNumber numberWithInteger:someIDYouHaveOfAnImage]};
[manager GET:methodURL parameters:parameterDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([responseObject isKindOfClass:[UIImage class]]) {
UIImage * image = responseObject;
// Here is your image object
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"failure getting the file : %@", error.localizedDescription);
}];
希望它有所帮助。
答案 3 :(得分:1)
https://github.com/AFNetworking/AFNetworking/archive/master.zip包含UIKit + AFNetworking目录