AFNetworking 2.0 setImageWithURLRequest
Posted
技术标签:
【中文标题】AFNetworking 2.0 setImageWithURLRequest【英文标题】: 【发布时间】:2013-10-04 03:08:58 【问题描述】:在我当前的一个项目中下载图像时,我正在使用此代码,但它不适用于 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 中使用的新代码有什么建议吗?谢谢!
【问题讨论】:
【参考方案1】:我使用此代码使其工作:
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];
但是我在使用这个占位符图像时遇到了另一个问题。有什么想法吗?
【讨论】:
【参考方案2】:您正在寻找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
。
【讨论】:
您是否关注了答案中的第一个链接? AFNetworking 2.0 的文档非常清晰:UIImageView(AFNetworking) 类别参考。如果您不确定自己在做什么,请不要对他人投反对票,我将不胜感激。【参考方案3】:使用更新的AFNetworking 2.0
(如果您的文件仅可用于下载,因此无法通过简单的 URL 访问):
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);
];
希望对你有帮助。
【讨论】:
我使用你的方法,但我不需要传递任何参数,我该怎么做,谢谢 你可以在发送参数时传递nil
。像这样:[manager GET:methodURL parameters:nil success:^(AFHTTPReques ...
【参考方案4】:
https://github.com/AFNetworking/AFNetworking/archive/master.zip 包含 UIKit+AFNetworking 目录
【讨论】:
以上是关于AFNetworking 2.0 setImageWithURLRequest的主要内容,如果未能解决你的问题,请参考以下文章