我需要使用HTTPBody of Array向服务器发送发布请求。这是我的参数数组:

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

现在,我需要将NSMutableURLRequestHTTPBody设置为此数组。我怎样才能做到这一点?

最佳答案

用您的参数创建可变请求。并尝试以下代码

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()

08-05 10:03