Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send image along with other parameters with AFNetworking

I am updating an old application code which used ASIHTTPRequest with AFNetworking. In my case, I am sending a bench of data to API, these data are different types: Image and other.

Here is the code I adopt so far, implementing an API client, requesting a shared instance, prepare the params dictionary and send it to remote API:

NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setValue:@"Some value" forKey:aKey];

[[APIClient sharedInstance]
 postPath:@"/post"
 parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     //some logic


 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     //handle error

 }];

What would be the case when I want to add an image to the params dictionary?

With ASIHTTPRequest, I used to do the following:

NSData *imgData = UIImagePNGRepresentation(anImage);

NSString *newStr = [anImageName stringByReplacingOccurrencesOfString:@"/"
                                                              withString:@"_"];



[request addData:imgData
    withFileName:[NSString stringWithFormat:@"%@.png",newStr]
  andContentType:@"image/png"
          forKey:anOtherKey];

I digged into AFNetworking documentation and found they appending the image in an NSMutableRequest like this:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

How should I mix this together on a neat way to integrate my image data into the APIClient request? Thanx in advance.

like image 992
Malloc Avatar asked May 22 '13 12:05

Malloc


2 Answers

I have used same AFNetworking to upload image with some parameter. This code is fine working for me. May be it will help out

NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
if (imageToUpload)
{
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, @"keyName", nil];

    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://------"]];

    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"API name as you have" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData: imageToUpload name:@"image" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
         //NSLog(@"response: %@",jsons);

     }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if([operation.response statusCode] == 403)
         {
             //NSLog(@"Upload Failed");
             return;
         }
         //NSLog(@"error: %@", [operation error]);

     }];

    [operation start];
}

Good Luck !!

like image 174
Ajay Chaudhary Avatar answered Sep 20 '22 13:09

Ajay Chaudhary


With AFNetworking 2.0.1 this code worked for me.

-(void) saveImage: (NSData *)imageData forImageName: (NSString *) imageName {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSString *imagePostUrl = [NSString stringWithFormat:@"%@/v1/image", BASE_URL];
    NSDictionary *parameters = @{@"imageName": imageName};

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:imagePostUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"image" fileName:imageName mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *op = [manager HTTPRequestOperationWithRequest:request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        DLog(@"response: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"Error: %@", error);
    }];
    op.responseSerializer = [AFHTTPResponseSerializer serializer];
    [[NSOperationQueue mainQueue] addOperation:op];
}

If JSON response is needed use:

op.responseSerializer = [AFJSONResponseSerializer serializer];

instead of

op.responseSerializer = [AFHTTPResponseSerializer serializer];
like image 38
appsmatics Avatar answered Sep 16 '22 13:09

appsmatics