swifthttprequestnsmutableurlrequestsparkcore

nsMutableUrl addvalue adding quotes "" around key


My end goal is a simple iPhone view with a switch that when turned "on", sends a post request to my Spark Core (wifi microchip) to turn on a relay.

I'm struggling to add params in a format that works for the post request. This works in a CLI:

curl https://api.spark.io/v1/devices/<myDeviceId>/led -d access_token=<myAccessToken> -d params=l1,LOW

This is my attempt to reproduce the request in swift:

func toggleLight (on: Bool){
    var urlToUse = sparkAPIBaseURL+coreId+lightsMethodName
    var url = NSURL.URLWithString(urlToUse)
    var request = NSMutableURLRequest(URL: url)
    var session = NSURLSession.sharedSession()

    request.HTTPMethod = "POST"

    if (on==true) {
        request.setValue(paramsForOn, forHTTPHeaderField: "params")
    } else {
        request.setValue(paramsForOff, forHTTPHeaderField: "params")
    }//if

    request.setValue(accessToken, forHTTPHeaderField: "access_token")

    println("request: \(request)")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println("response: \(response)")

        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        println(strData)
        self.responseDataLabel.text = strData
    })//task

    task.resume()  //no idea what this does
}//toggleLight

The println shows the request to have extraneous quotes around the key "access_token", which I believe to be the problem:

request: <NSMutableURLRequest: 0x7a62a450> { URL: https://api.spark.io/v1/devices/<myDeviceId>/led, headers: {
"access_token" = <myAccessToken>;
params = "l1,LOW"; } }

The response shows the error that the access token isn't found:

response: <NSHTTPURLResponse: 0x7b654c60> { URL: https://api.spark.io/v1/devices/<myDeviceId>/led } { status code: 400, headers {
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 104;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 27 Jul 2014 18:21:45 GMT";
Server = "nginx/1.6.0";
"X-Powered-By" = Express;} }{
"code": 400,
"error": "invalid_request",
"error_description": "The access token was not found"}

I tried setValue as well as addValue but they both seem to treat the key access_token by adding quotes and the value without quotes where key params doesn't have quotes and the value does.

Thanks!

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Stack won't let me answer my own question for a few more hours, so here's the working code that resolved the issue: Thanks Jonah - I learned from a friend that Spark Core requires the key value pairs in the body, so this is the working code that got me over the hump:

    func toggleLight (on: Bool){
    var urlToUse = sparkAPIBaseURL+coreId+lightsMethodName
    var url = NSURL.URLWithString(urlToUse)
    var request = NSMutableURLRequest(URL: url)
    var session = NSURLSession.sharedSession()

    request.HTTPMethod = "POST"

    var params: String
    if (on==true) {
        params = paramsForOn
    } else {
        params = paramsForOff
    }//if

    **var message = "access_token=\(accessToken)&params=\(params)"
    request.HTTPBody = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding)**

    println("request: \(request)")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in println("response: \(response)")

        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        println(strData)
        self.responseDataLabel.text = strData
    })//task

    task.resume()  //no idea what this does
}//toggleLight

Solution

  • Spark requires you to send the access token in the request body rather than the header.

    Try the following:

    var message = "access_token=<token>&params=<your_params>" 
    

    Then in the request:

    request.HTTPBody = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding)