1

我正在尝试编写一个方便的函数,该函数将接受图像标识符并使​​用 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];

4

1 回答 1

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:@""];
于 2013-02-20T00:28:24.813 回答