Chu*_*ump 8 macos post nsurlsession swift
我正在尝试在Swift 3开发快照中发出POST请求,但由于某种原因,对NSURLSession.dataTask的调用失败,标题中出现错误.
这是我正在使用的代码:
import Foundation
var err: NSError?
var params: Dictionary<String, String>
var url: String = "http://notreal.com"
var request = NSMutableURLRequest(url: NSURL(string: url)!)
var session = NSURLSession.shared()
request.httpMethod = "POST"
request.httpBody = try NSJSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTask(with: request, completionHandler: {data, response, err -> Void in
print("Entered the completionHandler")
})
task.resume()
Run Code Online (Sandbox Code Playgroud)
错误正是:
testy.swift:19:12: error: ambiguous reference to member 'dataTask(with:completionHandler:)'
var task = session.dataTask(with: request, completionHandler: {data, response, err -> Void in
^~~~~~~
Foundation.NSURLSession:2:17: note: found this candidate
public func dataTask(with request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Swift.Void) -> NSURLSessionDataTask
^
Foundation.NSURLSession:3:17: note: found this candidate
public func dataTask(with url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Swift.Void) -> NSURLSessionDataTask
Run Code Online (Sandbox Code Playgroud)
谁能告诉我:
谢谢!
编辑:我注意到有人在我之后写了这个问题的副本.这里的答案是更好的答案.
小智 23
使用URLRequeststruct.
在Xcode8中工作正常:
import Foundation
// In Swift3, use `var` struct instead of `Mutable` class.
var request = URLRequest(url: URL(string: "http://example.com")!)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) {data, response, err in
print("Entered the completionHandler")
}.resume()
Run Code Online (Sandbox Code Playgroud)
另外,出现此错误的原因是URLSession API具有相同的名称方法,但每个都采用不同的参数.
因此,如果没有明确的演员,API将会混淆.我认为这是API的命名错误.
发生此问题,代码如下:
let sel = #selector(URLSession.dataTask(with:completionHandler:))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12310 次 |
| 最近记录: |