ios 如何使用 AFNetworking 2.0 下载图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19501652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to download image with AFNetworking 2.0?
提问by raistlin
Appareantly there is no AFImageRequestOperation, but only AFImageResponseSerializerand frankly I don't get it or maybe I'm just looking too long through AFNetworking site... Downloading images with previous AFNetworking was like a charm. I'd hate to go back to older AFnetworking, since I did almost all stuff via the new version... Anyone?
显然没有AFImageRequestOperation,但AFImageResponseSerializer坦率地说,我不明白,或者我只是在 AFNetworking 网站上看得太久了……使用以前的 AFNetworking 下载图像就像一种魅力。我不想回到旧的 AFnetworking,因为我几乎所有的东西都是通过新版本完成的......有人吗?
回答by Bot
SO you want something like this for 2.0.
所以你想要 2.0 这样的东西。
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Response: %@", responseObject);
_imageView.image = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Image error: %@", error);
}];
[requestOperation start];
As mentioned by Adam you can also do something like the below if you are just wanting to throw it into an imageView
正如亚当所提到的,如果您只想将其放入 imageView,您也可以执行以下操作
[myImageView setImageWithURL:[NSURL URLWithString:@"http://sitewithimage.com/images/myimage.png"]];
回答by lbsweek
for old version, there is no responseSerializer, you can also
对于旧版本,没有 responseSerializer,你也可以
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
//requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Response: %@", responseObject);
_imageView.image = [UIImage imageWithData:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Image error: %@", error);
}];
[requestOperation start];
回答by Penkey Suresh
For people using AFNetworkingin Swift, above solutioncan be written as below
对于AFNetworking在 Swift 中使用的人,上面的解决方案可以写成如下
let requestOperation : AFHTTPRequestOperation = AFHTTPRequestOperation(request: urlRequest)
requestOperation.responseSerializer = AFImageResponseSerializer()
requestOperation.setCompletionBlockWithSuccess({ (requestOperation, responseObject) in
print(responseObject)
_imageView.image = responseObject as? UIImage
}) { (requestOperation, error) in
print(error)
}
requestOperation.start()

