objective-cafnetworkingafhttpclient

Download an image with AFHTTPClient


I'm trying do download a jpeg-file from a server with AFNetworking. It seems to succeed accessing the server but the responseObject is empty.

Following is the relevant code:

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:"https://api.test.info/"];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"application/json"];
[client setParameterEncoding:AFJSONParameterEncoding];
[client setAuthorizationHeaderWithUsername:@"username" password:@"password"];

[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"image/jpeg"]];
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

[client getPath:@"image/number1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
    NSData *test = responseObject;
    NSLog(@"%@", responseObject);
    NSLog(@"%@", test);
    [self.imgProfile setImage:[UIImage imageWithData:test]];
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"%@", error);
}];

Output of this code is: (null) (null)

That means responseObject and test are empty objects. If I use the same URL in my browser I get the picture back easily. Username and password are valid, because other requests work.

What do I need to change, to download the image?

Any help is appreciated.


Solution

  • You are telling the client to use a JSON request. JSON is not an image.

    If you want NSData then you can do this...

    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:"https://api.test.info/"];
    [client setAuthorizationHeaderWithUsername:@"username" password:@"password"];
    
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    [client getPath:@"image/number1" parameters:nil success:^(AFHTTPRequestOperation *operation, NSData responseObject){
        [self.imgProfile setImage:[UIImage imageWithData:responseObject]];
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
    

    Or, if self.imgProfile is a UIImageView then it's even easier...

    [self.imgProfile setImageWithURL:[NSURL URLWithString:@"https://api.test.info/image/number1"]];
    

    Not sure how this works with authorization though.

    Actually, this is what to do...

    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:"https://api.test.info/"];
    [client setAuthorizationHeaderWithUsername:@"username" password:@"password"];
    
    NSURLRequest *request = [client requestWithMethod:@"GET" path:@"image/number1" parameters:nil];
    
    [self.imgProfile setImageWithURLRequest:request placeholderImage:nil success:nil failure:nil];