So this HTML code submits the data in the correct format for me.
<form action="https://www.example.com/register.php" method="post" enctype="multipart/form-data">
Name: <input type="text" name="userName"><BR />
Email: <input type="text" name="userEmail"><BR />
Password: <input type="text" name="userPassword"><BR />
Avatar: <input type="file" name="avatar"><BR />
<input type="submit">
</form>
I've looked into a good number of articles on how to do a multipart/form-data POST on iOS, but none really explain what to do if there were normal parameters as well as the file upload.
Could you please help me with the code to POST this in Obj-C?
Thanks!
The process is as follows:
Create dictionary with the
userName
,userEmail
, anduserPassword
parameters.Determine the path for the image:
Create the request:
This is the method used above to build the body of the request:
The above uses the following utility methods:
Then submit the request. There are many, many options here.
For example, if using
NSURLSession
, you could createNSURLSessionUploadTask
:Or you could create a
NSURLSessionDataTask
:The above assumes that the server is just returning text response. It's better if the server returned JSON, in which case you'd use
NSJSONSerialization
rather thanNSString
methodinitWithData
.Likewise, I'm using the completion block renditions of
NSURLSession
above, but feel free to use the richer delegate-based renditions, too. But that seems beyond the scope of this question, so I'll leave that to you.But hopefully this illustrates the idea.
I'd be remiss if I didn't point that, much easier than the above, you can use AFNetworking, repeating steps 1 and 2 above, but then just calling: