Trouble with NSURLSession multipart/form-data post request
<p>Im having some trouble with sending text and images in the same post request to my server. I think the problem has to do with the way i set my boundary. </p>

<p>Im using swift with ios9. </p>

<p>I followed instructions here <a href="https://stackoverflow.com/questions/8564833/ios-upload-image-and-text-using-http-post">ios Upload Image and Text using HTTP POST</a>
doing my best to convert the obj-c into swift</p>

<p>however when i post a request to my server, whenever i try to access the post data such as $_POST["key"] i get an undefined index error. Here is the code i use to setup the http request, can anyone spot the error:</p>

<pre><code> func sendRegisterRequest(params:Dictionary&lt;String, String&gt;, withImage image: UIImage) {

    // https://stackoverflow.com/questions/8564833/ios-upload-image-and-text-using-http-post
    let url = NSURL(string: "MY_URL");
    let request = NSMutableURLRequest(URL: url!)
    // the boundary string : a random string, that will not repeat in post data, to separate post data fields.
    let boundaryConstant = "----------V2ymHFg03ehbqgZCaKO6jy--";

    // string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
    let fileParamConstant = "file";

    request.HTTPMethod = "POST"
    request.setValue("multipart/form-data; boundary=\(boundaryConstant)", forHTTPHeaderField: "Content-Type")


    // post body
    let body = NSMutableData();



    // add params (all params are strings)
    for (key, value) in params {
        body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
        body.appendData("Content-Disposition: form-data; name=\"\(key.stringByAddingPercentEncodingWithAllowedCharacters(.symbolCharacterSet())!)\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
        body.appendData("\(value.stringByAddingPercentEncodingWithAllowedCharacters(.symbolCharacterSet())!)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    }

    //print(body);
    // add image data
    let imageData = UIImageJPEGRepresentation(image, 1.0);

    body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    body.appendData("Content-Disposition: form-data; name=\"\(fileParamConstant)\"; filename=\"image\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    body.appendData(imageData!);
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);

    request.HTTPBody = body;
</code></pre>