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

前端之家收集整理的这篇文章主要介绍了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:))
原文链接:https://www.f2er.com/swift/319547.html

猜你在找的Swift相关文章