2017-07-19 181 views
0

我只想問一下。爲什麼我的POST請求不被髮送?代碼看起來很完美,Xcode顯示沒有錯誤。我正在使用Swift 3.你能幫我嗎?謝謝!我的代碼如下,我的帖子URL是here。再次感謝!POST請求沒有在Swift中發送

@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)") 
    } 


} 

回答

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

您需要使用:

let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in 
    // do stuff with response, data & error here 
    print(error) 
    print(response) 
}) 
task.resume() 

Get more info here