如何使用AFNetworking 2.0下载图像?
可能没有AFImageRequestOperation
,但只有AFImageResponseSerializer
,坦率地说,我不明白,也许我只是通过AFNetworking网站太长时间…与以前的AFNetworking下载图像就像一个魅力。 我不想回到老的AFnetworking,因为我通过新版本做了几乎所有的东西…任何人?
所以你想为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];
正如Adam提到的,如果你只是想把它放到一个imageView中,你也可以做下面的事情
[myImageView setImageWithURL:[NSURL URLWithString:@"http://sitewithimage.comhttp://img.dovov.commyimage.png"]];
对于旧版本,没有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];
对于在Swift中使用AFNetworking
人, 上面的解决scheme可以写成如下
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()