0

I am trying to upload a photo to a webservice, and I am using the following code:

NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:imageToUpload], 0.5);

// 1
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPMaximumConnectionsPerHost = 1;
[config setHTTPAdditionalHeaders:@{@"Content-Type":@"multipart/form-data"}];

// 2
NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

// for now just create a random file name, dropbox will handle it if we overwrite a file and create a new name..
NSString *urlString =[NSString stringWithFormat:@"https://ABC.co.uk/photos?api_key=MYAPIKEY" ];
NSURL *webUrl = [NSURL URLWithString:urlString];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:webUrl];
[request setHTTPMethod:@"POST"];

// 3
NSURLSessionUploadTask *uploadTask = [upLoadSession uploadTaskWithRequest:request fromData:imageData];

// 4
//    uploadView.hidden = NO;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

// 5
[uploadTask resume];

I receive an error 500, and I'm not sure what to do.

I have tried implementing AFNetworking, body data appending like This, This, and This. Yet, no luck.

The code above is from Ray Wenderlich's website: Here.

All I need to provide the server is this:

  1. file (the image)
  2. API Key (I tried using the NSMutableURLRequest's addValue:forHTTPHeaderField: but it didn't work, so I'm using it in the URL. I know it's not the best practice in terms of safety, but I'm getting so desperate as I've been working on this for over 10 hours! One step at the time!)
  3. The Content-Type to be multipart/form-data

That's all I need to provide, and yet I'm not getting anywhere!

Can anyone please help?

Thank you in advance

UPDATE 1: So I made some alterations to the URL structure, and added the API key as a dictionary in HTTPBody, and now I am getting error 403.

It seems really weird that apple has not made any effort to serialise this part of connection. Anyway. I really appreciate anyone helping out!

Community
  • 1
  • 1
Sep
  • 79
  • 1
  • 1
  • 8

1 Answers1

0

Try setting the Content-Type in the request as well:

[request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
cbiggin
  • 1,942
  • 1
  • 17
  • 18