加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 3 dev快照中的POST请求给出了“对成员’dataTask的模糊引

发布时间:2020-12-14 05:32:57 所属栏目:百科 来源:网络整理
导读:我正在尝试在 Swift 3开发快照中发出POST请求,但由于某种原因,对NSURLSession.dataTask的调用失败,标题中出现错误. 这是我正在使用的代码: import Foundationvar err: NSError?var params: DictionaryString,Stringvar url: String = "http://notreal.com"v
我正在尝试在 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:))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读