I am trying to send a UIImage take with the UIImagePickerController to a server POST along with other pertinent values. But I get at the line that tries to set the dictionary value @"image" to UIImageJPEGRepresentation(image, 1.0):
-(void)sendImageToServer:(UIImage *)image
{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4;
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:nil delegateQueue:queue];
NSURL *uploadURL = [NSURL URLWithString:@"http://...."];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSData *postData = [[NSData alloc] init];
[postData setValue:UIImageJPEGRepresentation(image, 1.0) forKey:@"image"];
[postData setValue:@"1" forKey:@"categories[0]"];
[postData setValue:@"4" forKey:@"categories[1]"];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:postData
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
NSError *err;
NSDictionary *JSONDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
NSLog(@"HTTP 200 response: %@", JSONDict);
});
} else {
NSLog(@"HTTP %ld status!", (long)httpResponse.statusCode);
}
} else {
NSLog(@"HTTP post image error: %@", error);
}
}];
[uploadTask resume];
}
JSON serialization does not work here, because images are not valid JSON values. If on the other hand I try:
...
NSMutableData *postData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:postData];
[archiver encodeObject:UIImageJPEGRepresentation(image, 1.0) forKey:@"image"];
[archiver encodeObject:@"1" forKey:@"categories[0]"];
[archiver encodeObject:@"4" forKey:@"categories[1]"];
[archiver finishEncoding];
//NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:NSJSONWritingPrettyPrinted error:&jsonError];
//Now you can post the json data
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:postData
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {...
The key:value pairs archived do not seem to get to the server as such. This must be a routinely iOS coding task.
Even if I just try:
NSError *jsonError;
NSData *postData = [NSJSONSerialization dataWithJSONObject:@{@"image":@"123",@"categories[0]":@"1",@"categories[1]":@"4"} options:NSJSONWritingPrettyPrinted error:&jsonError];
The server does not get any keys at all...