我正在更新ASIHTTPRequest
与AFNetworking
. 就我而言,我将一组数据发送到API
,这些数据是不同的类型:图像和其他。
这是我目前采用的代码,实现 API 客户端,请求共享实例,准备 params 字典并将其发送到远程 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
}];
当我想将图像添加到params
字典时会发生什么情况?
使用ASIHTTPRequest
,我曾经执行以下操作:
NSData *imgData = UIImagePNGRepresentation(anImage);
NSString *newStr = [anImageName stringByReplacingOccurrencesOfString:@"/"
withString:@"_"];
[request addData:imgData
withFileName:[NSString stringWithFormat:@"%@.png",newStr]
andContentType:@"image/png"
forKey:anOtherKey];
我深入研究了AFNetworking
文档,发现他们以这样的方式附加图像NSMutableRequest
:
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"];
}];
我应该如何以一种巧妙的方式将它们混合在一起以将我的图像数据集成到APIClient
请求中?提前谢谢。