我通过此代码将图像上传到服务器。它在iOS部署目标8.1版本中工作正常,但是当我尝试将部署目标更改为9.1版本时,返回数据变为空,因为9.0中不推荐使用[NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
。
这是问题所在。
sendAsynchronousRequest:queue:completionHandler:'不推荐使用:首先在iOS 9.0中弃用 - 使用[NSURLSession dataTaskWithRequest:completionHandler:](参见NSURLSession.h)。
但我无法使用NSURLSession
执行此操作。请帮助将此代码修改为NSURLSession
。
NSData *imageData = UIImageJPEGRepresentation(cameraImageViewOutlet.image, compression);
while ([imageData length] > maxFileSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(cameraImageViewOutlet.image, compression);
}
// Here is the uploading the image to server by POST
NSString *urlString1 = @"bfkgfdkhkghghj";
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] init];
[request1 setURL:[NSURL URLWithString:urlString1]];
[request1 setHTTPMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
// Here we are doing the image to multipart...
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request1 addValue:contentType forHTTPHeaderField:@"Content-Type"];
// sending the image parameter in (name=\"img_file[]\";) passed given parameter...
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: attachment; name=\"img_file[]\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//sending the parameter(name=\"contentTypeId\) passed given parameter...
NSString *param1 = @"1";
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"contentTypeId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request1 setHTTPBody:body];
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
NSMutableDictionary * uploadData = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:nil];