Swift 3 dev快照中的POST请求给出了“对成员’dataTask的模糊引用(with:completionHandler :)’

我正在尝试在 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()

错误正是:

testy.swift:19:12: error: ambiguous reference to member 'dataTask(with:completionHandler:)'
var task = session.dataTask(with: request,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,NSError?) -> Swift.Void) -> NSURLSessionDataTask

谁能告诉我:

>为什么它给了我这个错误
>如何使用仅基于最新的Swift开发快照在自定义参数中成功发出POST请求(在任何情况下我都无法使用其他第三方库)

谢谢!

编辑:我注意到有人在我之后写了这个问题的副本.这里的答案是更好的答案.

使用URLRequest结构.

在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,err in
    print("Entered the completionHandler")
}.resume()

另外,出现此错误的原因是URLSession API具有相同的名称方法,但每个都采用不同的参数.

因此,如果没有明确的演员,API将会混淆.我认为这是API的命名错误.

发生此问题,代码如下:

let sel = #selector(URLSession.dataTask(with:completionHandler:))

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...