如何使用swift 2.0

时间:2016-02-23 06:51:01

标签: swift2

我需要使用swift2.0中的nsurl会话将json请求参数发送到服务器。我不知道如何创建json请求params.i创建了这样的参数

让jsonObj = ["用户名":"管理员","密码":" 123"," DeviceId&#34 ;:" 87878"]

   // print("Params are \(jsonObj)")

    //request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(jsonObj, options: [])

    // or if you think the conversion might actually fail (which is unlikely if you built `params` yourself)

     do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonObj, options:.PrettyPrinted)
     } catch {
        print(error)
     }

但它没有ping到方法体,所以我得到了失败的响应

1 个答案:

答案 0 :(得分:2)

请尝试以下代码。

    let parameters = ["Username":"Admin", "Password":"123","DeviceId":"87878"] as Dictionary<String, String>
    let request = NSMutableURLRequest(URL: NSURL(string:YOURURL)!)

    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

    let task = session.dataTaskWithRequest(request) { data, response, error in
        guard data != nil else {
            print("no data found: \(error)")
            return
        }

        do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("Response: \(json)")
            } else {
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                print("Error could not parse JSON: \(jsonStr)")
            }
        } catch let parseError {
            print(parseError)// Log the error thrown by `JSONObjectWithData`
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
    }

    task.resume()

希望它适合你!!