简体   繁体   中英

Error 406 uploading image to server from swift ios

I am trying to upload an image from my iOS app written in swift and tried some codes I found about it but nothing works.

Uploading throung Postman works perfect. Here a screenshot of the request in Postman:

Uploading image with Postman

As you can see the API expects a the PUT request with a JSON with only one field called "avatar" and then the image in it. Also keep in mind the form-data. In the Headers I only send the token to do the authentication.

Said this, in the Swift code I try to send as params the array with only the "avatar" key with the image encoded:

func uploadImage(url: String){

    let httpMethod: String = "PUT"

    var token = getTokenFromNSUserDefaults()

    var imageDataJpeg = UIImageJPEGRepresentation(self.myImage, 0.9)
    var base64StringJpeg = imageDataJpeg.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image
    var base64StringJpeg2 = imageDataJpeg.base64EncodedStringWithOptions(nil) // encode the image

    var imageDataPng = UIImagePNGRepresentation(self.myImage)
    var base64StringPng = imageDataPng.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image
    var base64StringPng2 = imageDataPng.base64EncodedStringWithOptions(nil) // encode the image

    // API Request
    self.request(httpMethod, token: token, params:["avatar":base64StringPng2], url: url) { (succeeded: Bool, msg: String) -> () in
        var alert = UIAlertView(title: "Success!", message: msg, delegate: nil, cancelButtonTitle: "Okay.")
        if(succeeded) {
            println("Success")
        }
        else {
            println("Fail")
        }

        // Move to the UI thread
        dispatch_async(dispatch_get_main_queue(), { () -> Void in

        })
    }
}


//// API REQUEST ////
func request(httpMethod: String, token: String, params: Dictionary<String, AnyObject>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {

    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()

    request.HTTPMethod = httpMethod

    var err: NSError?

    if token != ""{
        request.addValue("JWT \(token)", forHTTPHeaderField: "Authorization")
    }

    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)

    ////Option 1
    request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
    request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Disposition")
    request.addValue("multipart/form-data", forHTTPHeaderField: "Accept")

    ////Option 2
    //request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
    //request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Disposition")
    //request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        println("Response: \(response)")
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Body: \(strData)")
        var err: NSError?

        var msg = "No message"

        let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &err)
        println("JSON: \(json)")

        if(err != nil) {
            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON1: '\(jsonStr)'")
            postCompleted(succeeded: false, msg: "Error")
        }
        else {

            self.parseJson(json!)

            postCompleted(succeeded: true, msg: "Works!")
            return
        }
    })

    task.resume()
}

Here's the log response from the server with always a 406 error message as follows (do not look at the "censored" url):

Response: <NSHTTPURLResponse: 0x7f967bed1450> { URL: https://***********************/ } { status code: 406, headers {
    Allow = "GET, PUT, DELETE, HEAD, OPTIONS";
    Connection = "keep-alive";
    "Content-Type" = "application/json";
    Date = "Wed, 02 Dec 2015 18:30:13 GMT";
    Server = "nginx/1.4.6 (Ubuntu)";
    "Transfer-Encoding" = Identity;
    Vary = Accept;
    "X-Frame-Options" = SAMEORIGIN;
} }
Body: Optional()
JSON: nil
The operation couldn’t be completed. (Cocoa error 3840.)
Error could not parse JSON1: 'Optional()'
Fail

Thank you very much for your help in advance!

您的“参数”不是JSON格式-缺少JSON字典的花括号。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM