对于POST请求,我使用以下代码:
private func post(url: String, params: [String: AnyObject], headers: [String: AnyObject]) {
let url = NSURL(string: apiUrl)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Application")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
} catch {
print("error")
//POST with completionHandler
var task = session.dataTaskWithRequest(url, completionHandler: { (data, response, error) -> Void in
print(data)
})
}
}
并且在var task = ...
最开始的行中出现此错误:Cannot convert value of type 'NSURL' to expected argument type 'NSURLRequest'
答案 0 :(得分:1)
更改此行:
var task = session.dataTaskWithRequest(url, completionHandler: { (data, response, error) -> Void in
并传递请求...而不是网址:
var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
总是读取你正在调用的方法名称,这是专门创建一个dataTask和REQUEST,xcode也应该突出显示。