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

时间:2014-11-20 09:41:35

标签: json post swift nsurlsession

我坚持使用以下代码。如何在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()

2 个答案:

答案 0 :(得分: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()

我建议使用AFNetworking。例如,请参阅Posting JSON data using AFNetworking 2.0

答案 1 :(得分:0)

这是您可以设置参数并发送 POST 请求的方法,使用 Alamofire 轻松实现。

  • Swift 2.2

    let URL = NSURL(string: "https://SOME_URL/web.send.json")!
    let mutableURLRequest = NSMutableURLRequest(URL: URL)
    mutableURLRequest.HTTPMethod = "POST"
    
    let parameters = ["api_key": "______", "email_details": ["fromname": "______", "subject": "this is test email subject", "from": "support@apple.com", "content": "<p> hi, this is a test email sent via Pepipost JSON API.</p>"], "recipients": ["_________"]]
    
    do {
        mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
    } catch {
        // No-op
    }
    
    mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    Alamofire.request(mutableURLRequest)
        .responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
    
            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
    }