Hi everyone and thanks in advance for any help providing in understanding in how to convert some NSURLConnection code into the newer NSURLSession. What I am trying to do is to make a POST request to a server, and send a photo base 64 encoded for the key "photo".
Below I have an working example written in NSURLConnection and I will like to convert it into NSURLSession.
As I read on the apple documentation from what I understood I should use a Data tasks because in my case it is an image and if it is a larger transfer like a video the I should use Upload tasks.
Regarding the upload task I have found the next tutorial but the problem is that in my case I also set a headers and also my content type should be multipart/form-data.
NSURL *url = [NSURL URLWithString:myLink];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:parameter1 forHTTPHeaderField:header1];
[request addValue:parameter2 forHTTPHeaderField:header2];
[request addValue:parameter3 forHTTPHeaderField:header3];
[request addValue:parameter4 forHTTPHeaderField:header4];
[request addValue:parameter5 forHTTPHeaderField:header5];
[request setHTTPBody:[UIImageJPEGRepresentation(avatarImage, 1.0) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
NSError *jsonError;
if(httpResp.statusCode == 200){
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if (!jsonError) {
[[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"photo_url"] forKey:@"avatarLink"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else {
NSString *errorCode = [NSString stringWithFormat:@"An error has occured while uploading the avatar: %ld", (long)httpResp.statusCode];
[GeneralUse showAlertViewWithMessage:errorCode andTitle:@"Error"];
}
}];
I will like to mention that I tried to build an working example using Ray Wenderlich tutorial but I was getting an error regarding the way I was setting my headers
Thank you in advance for any provided help!