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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…