如何使用NSDictionary添加Image并使用iOS中的POST方法将Array列表发送到服务器

时间:2016-05-04 07:03:48

标签: ios objective-c nsarray nsdictionary image-uploading

我正在开发一个项目,我需要在NSDictionary中添加多个NSArray对象,并且需要使用POST请求将NSArray发送到服务器。为此,我使用AFNetworking框架。好吧,一切都运行正常,直到我遇到了在数组中发送Image's对象的要求。 我尝试将图像数据作为base64字符串形式发送,但问题是,当我尝试发送数据时,这需要花费大量时间和一些时间,并且连接失败。好吧,我试着用其他方式压缩图像并发送它,但这里UIImage质量受到影响。所以任何人都可以帮助我以正确的方式做到这一点。 提前谢谢!

2 个答案:

答案 0 :(得分:0)

    NSData *imagedata =  UIImagePNGRepresentation(_imgaddcontact.image);
    NSString *base64 = [imagedata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];      
  NSMutableDictionary *parameterdiction = [NSMutableDictionary dictionary];
 [parameterdiction setObject:base64 forKey:@"Photo"];

    AFHTTPRequestOperation *op = [manager POST:@"<URL>" parameters:parameterdiction constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
    {
        if(imagedata != nil)
        {
            [formData appendPartWithFileData:imagedata name:@"Photo" fileName:@"image.png" mimeType:@"image/png"];
        }
    }

答案 1 :(得分:0)

您应该使用AFNetworking。将您的库拖放到项目中并在课程中导入AFNetworking.h,然后您可以执行以下操作,

  // This request only depends on afnetworking
  NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:imageUploadUrl parameters:tempDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

 // retrieve image by any way in my case below in your case whatever
 UIImageView *tempImageView = (UIImageView*)[self.view viewWithTag:imageViewBaseTag+i];
 UIImage *img = tempImageView.image; 
 NSData *imgData = UIImageJPEGRepresentation(img, 0.5);  //convert image to data to send

    [formData appendPartWithFileData:imgData name:[imageNameArray objectAtIndex:i] fileName:[imageNameArray objectAtIndex:i] mimeType:@"image/jpeg"];  // append image data to formdata to send server


} error:nil];



// This part is not depend on AFnetworking

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


    // handle your response here. you get respose in data parameter convert it in appropriate format like json or string and you can handle error also if occured

}]resume];

希望这会有所帮助:)