ios Swift 3 URLSession.shared() 对成员'dataTask(with:completionHandler:) 错误的不明确引用(错误)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37812286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)
提问by SwiftDeveloper
Hello I have working json parsing code for swift2.2 but when i use it for Swift 3.0 gives me that error
你好,我有用于 swift2.2 的 json 解析代码,但是当我将它用于 Swift 3.0 时给了我那个错误
ViewController.swift:132:31: Ambiguous reference to member 'dataTask(with:completionHandler:)'
ViewController.swift:132:31:对成员“dataTask(with:completionHandler:)”的不明确引用
My codes here
我的代码在这里
let listUrlString = "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
let myUrl = URL(string: listUrlString);
let request = NSMutableURLRequest(url:myUrl!);
request.httpMethod = "GET";
let task = URLSession.shared().dataTask(with: request) {
data, response, error in
if error != nil {
print(error!.localizedDescription)
DispatchQueue.main.sync(execute: {
AWLoader.hide()
})
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
if let parseJSON = json {
var items = self.categoryList
items.append(contentsOf: parseJSON as! [String])
if self.fromIndex < items.count {
self.categoryList = items
self.fromIndex = items.count
DispatchQueue.main.async(execute: {
self.categoriesTableView.reloadData()
AWLoader.hide()
})
}else if( self.fromIndex == items.count){
DispatchQueue.main.async(execute: {
AWLoader.hide()
})
}
}
} catch {
AWLoader.hide()
print(error)
}
}
task.resume()
Thanks for ideas.
谢谢你的想法。
回答by Eric Aya
The compiler is confused by the function signature. You can fix it like this:
编译器被函数签名弄糊涂了。你可以像这样修复它:
let task = URLSession.shared.dataTask(with: request as URLRequest) {
But, note that we don't have to cast "request" as URLRequest
in this signature ifit was declared earlier as URLRequest
instead of NSMutableURLRequest
:
但是,请注意,如果之前声明为而不是,我们不必像URLRequest
在此签名中那样强制转换“请求” :URLRequest
NSMutableURLRequest
var request = URLRequest(url:myUrl!)
This is the automatic casting between NSMutableURLRequest
and the new URLRequest
that is failing and which forced us to do this casting here.
这是失败的和NSMutableURLRequest
新的之间的自动转换URLRequest
,这迫使我们在这里进行转换。
回答by HenryRootTwo
You have init'd myRequest
as NSMutableURLRequest
, you need this:
你已经初始化myRequest
为NSMutableURLRequest
,你需要这个:
var URLRequest
Swift is ditching both the NSMutable...
thing. Just use var
for the new classes.
斯威夫特正在放弃这两NSMutable...
件事。仅var
用于新课程。
回答by Saumil Shah
Xcode 8 and Swift 3.0
Xcode 8 和 Swift 3.0
Using URLSession:
使用 URLSession:
let url = URL(string:"Download URL")!
let req = NSMutableURLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()
URLSession Delegate call:
URLSession 委托调用:
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
print("downloaded \(100*writ/exp)" as AnyObject)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
}
Using Block GET/POST/PUT/DELETE:
使用块 GET/POST/PUT/DELETE:
let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:"Your request timeout time in Seconds")
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers as? [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
let httpResponse = response as? HTTPURLResponse
if (error != nil) {
print(error)
} else {
print(httpResponse)
}
DispatchQueue.main.async {
//Update your UI here
}
}
dataTask.resume()
Working fine for me.. try it 100% result guarantee
对我来说工作正常.. 尝试 100% 结果保证
回答by liwp_Stephen
This problem is caused by URLSession has two dataTask methods
这个问题是由 URLSession 有两个 dataTask 方法引起的
open func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask
open func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask
The first one has URLRequest
as parameter, and the second one has URL
as parameter, so we need to specify which type to call, for example, I want to call the second method
第一个有URLRequest
作为参数,第二个有URL
作为参数,所以我们需要指定要调用的类型,例如我想调用第二个方法
let task = URLSession.shared.dataTask(with: url! as URL) {
data, response, error in
// Handler
}
回答by Zhanserik
In my case error was in NSURL
在我的情况下,错误是在NSURL 中
let url = NSURL(string: urlString)
In Swift 3 you must write just URL:
在 Swift 3 中,你必须只写URL:
let url = URL(string: urlString)
回答by Naren
For Swift 3 and Xcode 8:
对于 Swift 3 和 Xcode 8:
var dataTask: URLSessionDataTask?
if let url = URL(string: urlString) {
self.dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let error = error {
print(error.localizedDescription)
} else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
// You can use data received.
self.process(data: data as Data?)
}
})
}
}
//Note: You can always use debugger to check error
//注意:您可以随时使用调试器来检查错误
回答by Alisha G
In swift 3 the compiler is confused by the function signature. Specifying it will clear the error. Also convert the url string to type URL. The following code worked for me.
在 swift 3 中,编译器被函数签名弄糊涂了。指定它将清除错误。还将 url 字符串转换为类型 URL。以下代码对我有用。
let urlString = "http://bla.com?batchSize="
let pathURL = URL(string: urlString)!
var urlRequest = URLRequest(url:pathURL)
let session = URLSession.shared
let dataTask = session.dataTask(with: urlRequest as URLRequest) { (data,response,error) in
回答by Josh
Short and concise answer for Swift 3:
Swift 3 的简短回答:
guard let requestUrl = URL(string: yourURL) else { return }
let request = URLRequest(url:requestUrl)
URLSession.shared.dataTask(with: request) {
(data, response, error) in
...
}.resume()
回答by SwiftDeveloper
Tested xcode 8 stable version ;Need to use var request
variable with URLRequest()
With thats you can easily fix that (bug)
已测试 xcode 8 稳定版;需要使用var request
变量与那URLRequest()
你可以很容易地修复(错误)
var request = URLRequest(url:myUrl!)
And
var request = URLRequest(url:myUrl!)
和
let task = URLSession.shared().dataTask(with: request as URLRequest) { }
Worked fine ! Thank you guys, i think help many people. !
工作得很好!谢谢你们,我想帮助了很多人。!
回答by Nikunj Patel
// prepare json data
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData
// create post request
let url = NSURL(string: "http://httpbin.org/post")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData as Data
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
return
}
do {
let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
print("Result",result!)
} catch {
print("Error -> \(error)")
}
}
task.resume()