从AFImageRequestOperation中的成功块返回图像

时间:2013-02-20 00:09:56

标签: iphone ios objective-c cocoa afnetworking

我正在尝试编写一个便捷功能,它将接受图像标识符并使​​用AFNetworking的AFImageRequestOperation下载图像。该函数正确下载图像,但我无法在成功块中返回UIImage。

-(UIImage *)downloadImage:(NSString*)imageIdentifier
{
  NSString* urlString = [NSString stringWithFormat:@"http://myserver.com/images/%@", imageIdentifier];

  AFImageRequestOperation* operation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] imageProcessingBlock:nil
  success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
  {
    NSLog(@"response: %@", response);
    return image;                                                   
  }
  failure:nil];

[operation start];

}

return image;行给出了错误:

Incompatible block pointer types sending 'UIImage *(^)(NSURLRequest *__strong, NSHTTPURLResponse *__strong, UIImage *__strong)' to parameter of type 'void (^)(NSURLRequest *__strong, NSHTTPURLResponse *__strong, UIImage *__strong)' 

关于发生了什么的任何想法?我很乐意能够致电

UIImage* photo = [downloadImage:id_12345];

1 个答案:

答案 0 :(得分:3)

AFNetworking图像下载操作是异步的,您无法在操作开​​始时分配它。

您尝试构建的函数应该使用委托或块。

- (void)downloadImageWithCompletionBlock:(void (^)(UIImage *downloadedImage))completionBlock identifier:(NSString *)identifier {
  NSString* urlString = [NSString stringWithFormat:@"http://myserver.com/images/%@", identifier];

  AFImageRequestOperation* operation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] imageProcessingBlock:nil
  success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
  {
    NSLog(@"response: %@", response);
    completionBlock(image);                                                   
  }
  failure:nil];

  [operation start];
}

像这样称呼它

// start updating download progress UI
[serverInstance downloadImageWithCompletionBlock:^(UIImage *downloadedImage) {
  myImage = downloadedImage;
  // stop updating download progress UI
} identifier:@""];