开发者社区> 问答> 正文

关于AFImageRequestOperation返回图片 的问题

要写一个应用,用来接受图片标示符,并且使用 AFNetworkingAFImageRequestOperation 下载图片。

目前下载已经成功了,但是在block中无法返回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];
`

展开
收起
爵霸 2016-03-24 12:43:59 2014 0
1 条回答
写回答
取消 提交回答
  • AFNetworking图片下载操作是异步的,你不能在操作开始的时候指定它。

    你构建的函数应该用delegates和block。

    - (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:@""];
    2019-07-17 19:12:35
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载