如何在swift中使用NSURLSession来发布JSON数据

dha*_*hah 1 post json nsurlsession swift

我坚持使用下面的代码.如何设置param和post方法?

let params:[String:Any] = [
        "email" : usr,
        "userPwd" : pwdCode]

let url = NSURL(string:"http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthentication")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

request.HTTPBody = params<what should do for Json parameter>


let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode != 200 {
            println("response was not 200: \(response)")
            return
        }
    }
    if error {
        println("error submitting request: \(error)")
        return
    }

    // handle the data of the successful response here
}
task.resume()
Run Code Online (Sandbox Code Playgroud)

sur*_*rui 5

如果我正确理解了这个问题

var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
var usr = "dsdd"
var pwdCode = "dsds"
let params:[String: AnyObject] = [
    "email" : usr,
    "userPwd" : pwdCode ]

let url = NSURL(string:"http://localhost:8300")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)

let task = session.dataTaskWithRequest(request) {
    data, response, error in

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode != 200 {
            println("response was not 200: \(response)")
            return
        }
    }
    if (error != nil) {
        println("error submitting request: \(error)")
        return
    }

    // handle the data of the successful response here
    var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
    println(result)
}
task.resume()
Run Code Online (Sandbox Code Playgroud)

我建议使用AFNetworking.例如,请参阅使用AFNetworking 2.0发布JSON数据.