1

I've been searching a while for a solution to this problem but everyone seems to be on the opposite side that I'm on.

I'm writing some swift code to receive a multipart/form-data response from a Django REST API (also written by me). The response contains a JSON object as well as a single .png file. The response body looks as such right before it is sent from the API to the swift module:

--$AGORA_boundary$
Content-Disposition: form-data; name="json"

{"category": "Household", "post_id": "226"}
--$AGORA_boundary$
Content-Disposition: form-data; name="image"; filename="image_name"
Content-Type: image/png

.....image data.....
--$AGORA_boundary$--

Which, by HTTP standards, is correctly formatted as a multi-part/form-data response. The response content-type is:

multipart/form-data; boundary=$AGORA_boundary$

The swift module follows the NSURLSession.dataTaskWithRequest model

var image1Task = session.dataTaskWithRequest(image1Request,completionHandler: {data, response, error -> Void in
    //completionhandler code here
    //how do I parse the response data to receive the JSON object
    // and the the image data?
}

I have no idea how to parse the multipart data object, and every research try for a swift multipart response yields results where people are attempting to SEND a multipart REQUEST; not the side I am trying to solve.

So, how can I parse the incoming data into the two parts: JSON and image?

Thanks ahead of time for any help!

Freestyle076
  • 1,548
  • 19
  • 36
  • 1
    Since you own the server can you send the image base64-encoded with the JSON and eliminate the multipart response? – sbooth Mar 19 '15 at 00:13
  • That's what we're trying to avoid. Encoding the image is hugely inefficient, we're hoping a multipart response will increase speed. – Freestyle076 Mar 19 '15 at 00:16
  • There is some Obj-C code in http://stackoverflow.com/questions/22095186/parse-multipart-response-for-image-download-in-ios that looks reasonable. – sbooth Mar 19 '15 at 00:19
  • @Freestyle076 I'm also interested in the inefficiencies of this, as I'm sending base64-encoded JSON instead of multipart to make my life easier. Have you done any actual comparisons between the size of the data with each process, with compression turned on on your server? I'd mostly been assuming that a gzip-encoded JSON transfer won't actually be hugely inefficient compared to a multipart... Or is it not size you're worried about? – Matt Gibson Mar 19 '15 at 07:09

0 Answers0