你好我有工作json解析swift2.2的代码,但是当我用它为Swift 3.0给我错误
ViewController.swift:132:31:对成员' dataTask的不明确引用(with:completionHandler:)'
我的代码在这里
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()
感谢您的想法。
答案 0 :(得分:300)
编译器被函数签名搞糊涂了。你可以像这样解决它:
let task = URLSession.shared.dataTask(with: request as URLRequest) {
但是,请注意,我们不必投出&#34;请求&#34;作为此签名中的URLRequest
,如果之前已将其声明为URLRequest
而不是NSMutableURLRequest
:
var request = URLRequest(url:myUrl!)
这是NSMutableURLRequest
与失败的新URLRequest
之间的自动投射,迫使我们在此处进行投射。
答案 1 :(得分:32)
您已将myRequest
初始化为NSMutableURLRequest
,您需要:
var URLRequest
斯威夫特放弃了NSMutable...
这件事。只需使用var
作为新类。
答案 2 :(得分:17)
Xcode 8和Swift 3.0
使用网址:
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委托电话:
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){
}
使用Block 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()
为我工作正常..试试100%结果保证
答案 3 :(得分:12)
这个问题是由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
第一个有URLRequest
作为参数,第二个有URL
作为参数,所以我们需要指定要调用的类型,例如,我想调用第二个方法
let task = URLSession.shared.dataTask(with: url! as URL) {
data, response, error in
// Handler
}
答案 4 :(得分:9)
在我的情况下,错误出现在 NSURL
中let url = NSURL(string: urlString)
在Swift 3中,您必须只写网址:
let url = URL(string: urlString)
答案 5 :(得分:3)
经过测试的xcode 8稳定版; 需要将var request
变量与URLRequest()
一起使用你可以轻松修复它( bug )
var request = URLRequest(url:myUrl!)
和
let task = URLSession.shared().dataTask(with: request as URLRequest) { }
工作得很好!谢谢你们,我想帮助很多人。 !
答案 6 :(得分:3)
对于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?)
}
})
}
}
//注意:您始终可以使用调试器来检查错误
答案 7 :(得分:3)
在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
答案 8 :(得分: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()
答案 9 :(得分:2)
// 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()
答案 10 :(得分:2)
要通过GET请求加载数据,您不需要任何URLRequest
(并且没有分号)
let listUrlString = "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
let myUrl = URL(string: listUrlString)!
let task = URLSession.shared.dataTask(with: myUrl) { ...
答案 11 :(得分:2)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data,response,error in
if error != nil{
print(error!.localizedDescription)
return
}
if let responseJSON = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String:AnyObject]{
if let response_token:String = responseJSON["token"] as? String {
print("Singleton Firebase Token : \(response_token)")
completion(response_token)
}
}
})
task.resume()
答案 12 :(得分:1)
对我来说,我这样做是为了找到,
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in ...}
无法使用
"let url = NSURL(string: urlString)
答案 13 :(得分:1)
这对我有用:
let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
...
密钥已添加到URLSessionDataTask
类型声明中。