Search code examples
apiswiftpostnsurlsessionmashape

POST request in swift


Okay I have looked high and low and can not find the answer. So I am just trying to make a simple POST request to a mashape api from an iPhone app. Here is what I have so far:

var headers: NSDictionary = ["X-Mashape-Key": "Hm5NokCvUamshPFfnQCRJKne3UuCp1C******************", "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"]

var params = ["async": "0", "client_secret": "ceaf93f10f7330318ae*********************", "input": "<required>", "lang": "En", "memory_limit": "262144", "source": "From the web", "time_limit": "10"] as Dictionary

var url : NSURL = NSURL(string: "https://blah.mashape.com/location/")!

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

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) as NSData!

if err != nil {
    println(err)
}

request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers

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

task.resume()

But the strData says this this when I get the response:

Body: Optional({"errors": {}, "code_id": "cc6581D", "message": "ArgumentMissingError: client_secret is needed!", "run_status": {"status": "AC", "time_limit": 5, "output_html": "a[0]&nbsp;=&nbsp;10<br>a[1]&nbsp;=&nbsp;11<br>a[2]&nbsp;=&nbsp;12<br>a[3]&nbsp;=&nbsp;13<br>a[4]&nbsp;=&nbsp;14<br>a[5]&nbsp;=&nbsp;15<br>a[6]&nbsp;=&nbsp;16<br>a[7]&nbsp;=&nbsp;17<br>a[8]&nbsp;=&nbsp;18<br>a[9]&nbsp;=&nbsp;19<br>", "memory_limit": 262144, "time_used": "0.1006", "signal": "OTHER", "status_detail": "N/A", "output": "a[0] = 10\na[1] = 11\na[2] = 12\na[3] = 13\na[4] = 14\na[5] = 15\na[6] = 16\na[7] = 17\na[8] = 18\na[9] = 19\n", "async": 0, "memory_used": "64"}, "compile_status": "OK", "web_link": "http://blah.com/cc6581D"})

it says that the client_secret is needed but I include it in the params dictionary? Any help would be appreciated!


Solution

  • Okay incase anyone has the same problem I am going to post the solution. So as @findall pointed out I the correct encoding was not JSON and it was just supposed to be a url encode. But after I changed it to url encode it still was not working. So I gave AlamoFire a shot and it totally worked! Here is the code:

    var headers: NSDictionary = ["X-Mashape-Key": "Hm5NokCvUamshPFfnQCRJKne3UuCp1Cq48FjsnMnQnEcHN0gk6", "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"]
    
    var params = ["async": "0", "client_secret": "ceaf93f10f7330**************************", "input": "<required>", "lang": "En", "memory_limit": "262144", "source": "Link", "time_limit": "10"] as Dictionary
    
    var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
    defaultHeaders["X-Mashape-Key"] = "Hm5NokCvUamshPFfnQ********************************"
    defaultHeaders["Content-Type"] = "application/x-www-form-urlencoded"
    defaultHeaders["Accept"] = "application/json"
    
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = defaultHeaders
    
    let manager = Alamofire.Manager(configuration: configuration)
    
    var request = Alamofire.Manager(configuration: configuration).request(.POST, "https://blah.mashape.com/location/", parameters: params)
    request.responseString({ (request, response, string, error) in
    
        println(string)
    })
    

    Thank you @chris for telling me about AlamoFire.