POST请求未在Swift中发送

时间:2017-07-19 08:35:44

标签: swift xcode post swift3

我想问一下。为什么我的POST请求下面没有发送?代码看起来非常完美,Xcode没有显示任何错误。我正在使用Swift 3.你能帮助我吗?谢谢!我的代码如下,我的帖子网址为here。再次感谢!

@IBAction func onClick(_ sender: Any) {
    let username = Username.text
    let password = Password.text

    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"

    let params = ["username": username, "password": password] as Dictionary<String, AnyObject>

    do {
        try request.httpBody = JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    } catch {
        print("Error")
    }

    request.addValue("application/JSON", forHTTPHeaderField: "Content-Type")

    URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in
        NSLog("open tasks: \(openTasks)")
    }


}

2 个答案:

答案 0 :(得分:3)

您需要使用:

lang_detect

Get more info here

答案 1 :(得分:1)

您必须使用URLSession.shared.dataTask(with:completionHandler:)。另外,请勿使用NSMutableRequest,但请使用原生的Swift版本URLRequest

@IBAction func onClick(_ sender: Any) {
    let username = Username.text
    let password = Password.text

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let params = ["username": username, "password": password] as Dictionary<String, AnyObject>

    do {
        try request.httpBody = JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    } catch {
        print("Error")
    }

    request.addValue("application/JSON", forHTTPHeaderField: "Content-Type")

    URLSession.shared.dataTask(with: request, completionHandler: { data,response, error in
        if let existingError = error {
            //handle error
        }
        //handle response and/or data
    }).resume()
}