在使用swift 2.2時,在使用NSURLSession時我沒有得到Response。我究竟做錯了什麼?在NSURLSession中沒有得到結果
我必須在POST請求中傳遞參數和標題。
func API() {
let userName:String! = "uname"
let password:String! = "password"
let request = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = "POST"
let data = try! NSJSONSerialization.dataWithJSONObject(parameter, options:[])
let json = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
request.HTTPBody = json.dataUsingEncoding(NSUTF8StringEncoding)
request.allHTTPHeaderFields = ["key":"value"]
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
結果是:
responseString =可選( 「」)
如果你要送你必須相應地設置頁眉JSON。 – vadian
我已更新代碼,試圖發送標題,但它仍然無法正常工作 – user7205007