Uploading files to the server from the app.
I expected this one to be trivial and follow mostly like the last one. But like with all others, it was no so.
Before I get into, lets lay out a basic example of where we might use this in our app. The answer is pretty much anyplace where you would want user generated media within the app. So anything that is user generated non-text data. We go with the most basic example of a photo upload. One place where users might want to upload a photo is in their User Profile Page.
From the iOS side of things, most of what is mentioned can be done by calling simple methods on objects that encapsulate the information we are trying to send. However, sending file data through HTTP Requests has this very weird format. The mechanism looks almost more low level than what I am usually used to.
We obtain a JPEG representation of our image and encode it in an instance of NSData. Then, like before we create a HTTP POST Request and set its fields like Content-Type, Content-Length, etc. The Request calls a script and provides the image data to the script to upload to the file system.
We encode the image data (NSData) into the body of the HTTP request. Also you have to encode into the body, information that what this data means - in this case it's an image - and also information about where to store it.
The way to do this is that each section of information in the body is preceded by a tag defining what the content actually is. So, one section might be the declaration that the data being sent is an image, while another is the image data itself. In case of multiple images being uploaded there are multiple sections each containing the data of a single image. Sections are divided by a boundary string that you have to define. The boundary string is simply a random string that can never appear in your data. This is what I meant when I said low level. It is used as a marker to divide the "multipart" data that you are trying to send.
When the request is properly defined and sent, the calling script can access the file data (in this case picture data) in PHP $_FILES variable. Then you have to call move_uploaded_file to upload the file. Also in the script, you may wish to do other things such as rename the file, select the location where you want to save the image and so on.
















