Search code examples
iosswiftnsurlrequest

NSMutableURLRequest - HTTPBody from Swift Array


I need to send a post request to my server with HTTPBody of Array. Here's my array of parameters:

params = [
            "message"  : [
                "alert" : "Find your iPhone",
                "sound" : "Binocular_Default.caf"
            ]
        ]

Now I need to set NSMutableURLRequest's HTTPBody to this array. How can I do that?


Solution

  • Create mutable request with your params. and try with following code

    var request = NSMutableURLRequest(URL: NSURL(string: "yoururl"))
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    
    //create dictionary with your parameters
    var params = ["username":"test", "password":"pass"] as Dictionary<String, String>
    
    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    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 json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
    
        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            println(err!.localizedDescription)
        }
        else {
    
        }
    })
    
    task.resume()