【问题标题】:How to download image with AFNetworking 2.0?如何使用 AFNetworking 2.0 下载图像?
【发布时间】:2013-10-30 08:47:13
【问题描述】:

显然没有AFImageRequestOperation,但只有AFImageResponseSerializer,坦率地说,我不明白,或者我只是通过AFNetworking 网站看了太久......用以前的AFNetworking 下载图像就像一个魅力。我不想回到旧的 AFnetworking,因为我几乎所有的东西都是通过新版本完成的……有人吗?

【问题讨论】:

    标签: iphone ios xcode afnetworking-2


    【解决方案1】:

    所以你想要这样的 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.com/images/myimage.png"]];
    

    【讨论】:

    • 救了我的命 :) 我知道有一些解决办法 :)
    • 这是在主队列还是后台队列?
    • @Tander 完成块在主队列上运行
    • 这个答案很好,但请查看github.com/AFNetworking/AFNetworking/blob/master/…,如果您只是将图像放入图像视图中,那么您已经完成了很多工作
    • Bot 的回答是完成块是正确的,尽管只是简化了一点。 AFURLConnectionOperation 上有一个completionQueue 属性,您可以使用它来指定使用的队列。默认是主队列。 :)
    【解决方案2】:

    老版本,没有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];
    

    【讨论】:

      【解决方案3】:

      对于在 Swift 中使用 AFNetworking 的人,above solution 可以写成如下

          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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多