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