How to download image with AFNetworking 2.0?

后端 未结 3 913
臣服心动
臣服心动 2020-12-04 11:57

Appareantly there is no AFImageRequestOperation, but only AFImageResponseSerializer and frankly I don\'t get it or maybe I\'m just looking too long

相关标签:
3条回答
  • 2020-12-04 12:31

    For people using AFNetworking in Swift, above solution can be written as below

        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()
    
    0 讨论(0)
  • 2020-12-04 12:39

    for old version, there is no responseSerializer, you can also

    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];
    
    0 讨论(0)
  • 2020-12-04 12:55

    SO you want something like this for 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];
    

    As mentioned by Adam you can also do something like the below if you are just wanting to throw it into an imageView

    [myImageView setImageWithURL:[NSURL URLWithString:@"http://sitewithimage.com/images/myimage.png"]];
    
    0 讨论(0)
提交回复
热议问题