Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between multipart form upload and NSURLSession.uploadTaskWithRequest

Coming from the world of web programming, I'm pretty much comfortable with working with multipart form requests to upload files. However, in iOS, we have a thing called NSURLSession with the method uploadTaskWithRequest, which seems to be the method to call to do image uploads and the likes.

Can you explain the difference between the two approach, multipart form upload vs uploadTaskWithRequest? If I already have a backend that handle multipart form uploads, what kind of adjustments that I might need so that it support uploadTaskWithRequest as well?

like image 763
Andree Avatar asked Oct 14 '15 06:10

Andree


1 Answers

The uploadTaskWithRequest simply sends the NSData, file, or stream as the body of the request. It doesn't do anything beyond that. It simply has the benefit that it can be used with background sessions.

So, if you have web service that is expecting multipart/form-data request, you have to build that request yourself (unless you use something like AFNetworking or Alamofire to do this for you). Once you've built that request, you can either use dataTaskWithRequest (having set the HTTPBody of the NSMutableURLRequest) or uploadTaskWithRequest (in which case you don't set HTTPBody, but rather provide it as a parameter to uploadTaskWithRequest).

By the way, a tool like Charles is very useful in these cases, letting you observe what's going on behind the scenes.

like image 104
Rob Avatar answered Sep 28 '22 23:09

Rob