AFNetworking在嵌套json的字典数组中发布图像

时间:2015-08-06 05:40:08

标签: ios objective-c afnetworking

如何发送嵌套的json请求,其中包含一个字典数组中的图像:

    @{"Contact" : @[@{
                "id" : "x1",
                "name" : "my product1",
                "image" : #<image1>
               },
               {
                "id" : "x2",
                "name" : "my product2", 
                "image" : #<image2>
              }] 
            }; 

我们正在参考此链接 AFNetworking post image in nested json

1 个答案:

答案 0 :(得分:0)

试试这个

  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"];
 }];