0

I need to upload a file to a server and the request has to specify some form parameters. How can I do this with the NSURLSessionUploadTask? In other words, how can I send a multipart POST request.

cheers

Jan
  • 7,444
  • 9
  • 50
  • 74

2 Answers2

1

When using NSURLSessionUploadTask, you don't call setHTTPBody on the NSMutableURLRequest (like we used to do with NSURLConnection), but rather you include this in the NSData or file passed to the NSURLSession method, uploadTaskWithRequest (or in the stream we supply for uploadTaskWithStreamedRequest).

In terms of creating the body of the request, itself, you have to do this yourself. Obviously, a framework like AFNetworking can greatly simplify this process.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • so basically I have to build the body myself, right ? – Jan May 25 '14 at 20:23
  • @Jan Yep, unless you use a framework like AFNetworking. – Rob May 25 '14 at 20:26
  • @Rob I am uploading files using a background session, which only support from file, I also need to send a multiform request, my NSURLRequest right now includes the multi form part and the NSData of the file a photo in this case, and I got it to work using NSURLSessionDownloadTask in the background, which is a work around, but doesn't seem right at all. I see you mention, that we can include the data in the file itself, how would I go about doing this?, would it be a file containing the multi form request and the nsdata of the image?, any links or documentation on how to do this would be great. – Oscar Gomez Mar 11 '15 at 17:09
  • 1
    @Rob Note that i can actually use use an uploadTaskWithStreamedRequest in the background but only on iOS 8 and it works just fine, but it fails on iOS 7 with the assertion on background upload only supported from a file. I still have to support 7 unfortunately. – Oscar Gomez Mar 11 '15 at 17:11
  • 1
    @OscarGomez Then put your your full upload request body in a separate file and upload that. – Rob Mar 11 '15 at 17:16
  • 1
    @Rob Thanks Rob I though about doing that, shortly after writing this, and it worked! thank you, it is an inconvenience that I have to save it to a file first though. – Oscar Gomez Mar 11 '15 at 17:46
0

https://github.com/pyke369/PKMultipartInputStream

This library can generate the multipart request pretty well.

Jan
  • 7,444
  • 9
  • 50
  • 74