在你读这篇文章之前,请理解我是斯威夫特的初学者,我正在努力学习。我浏览了一些网站,希望得到答案,但我要么找不到,要么做错了。我一直在学习本教程,但这是旧的,没有更新的>>我所遵循的教程<<
我也试图修改一些,使之成为斯威夫特3--尽管我可能做得不对。
我如何正确地完成URLSession?我知道这个错误:
从类型为‘( _,_,_)的抛出函数到非抛出函数类型的无效转换
这一行如下:
让任务: URLSessionDataTask =session.dataTask(带有: completionHandler:{data,response,error -> Void )
对于变量"jsonDict“-我得到了我的错误
额外的arg‘错误’在呼叫。
提前感谢
var urlString:String = ("http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN "+stringQuotes+"&format=json&env=http://datatables.org/alltables.env").addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
var url : URL = URL(string: urlString)!
var request: URLRequest = URLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task : URLSessionDataTask = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
if((error) != nil) {
println(error.localizedDescription)
}
else {
var err: NSError?
var jsonDict = try JSONSerialization.JSONObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers, error: &err) as NSDictionary
if(err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
else {
var quotes:NSArray = ((jsonDict.objectForKey("query") as NSDictionary).objectForKey("results") as NSDictionary).objectForKey("quote") as NSArray
DispatchQueue.main.async(execute: {
.default.post(name: Notification.Name(rawValue: kNotificationStocksUpdated), object: nil, userInfo: [kNotificationStocksUpdated:quotes])
})
}
}
})
task.resume()
}发布于 2016-11-22 02:34:43
请查找SWIFT3.0的更新代码
var urlString:String = ("http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN "+stringQuotes+"&format=json&env=http://datatables.org/alltables.env").addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
let url : URL = URL(string: urlString)!
let request: URLRequest = URLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print(error?.localizedDescription ?? "")
}
else{
do{
let jsonDict:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
let quotes:NSArray = ((jsonDict.object(forKey: "query") as! NSDictionary).object(forKey: "results") as! NSDictionary).object(forKey: "quote") as! NSArray
print(quotes)
}
catch{
print(error.localizedDescription)
}
}
};
task.resume()注意:,我还没有测试代码。因为您还没有指定URL的参数
发布于 2016-11-22 02:16:03
您的问题不在于URLSessionDataTask,而在于您的completionHandler。更具体地说,在var jsonDict = try JSONSerialization...位中。try表示您的代码可以抛出异常,但不处理它(catch)。这就是为什么编译器决定您的完成处理程序是(_, _, _) throws -> Void类型,而dataTask方法需要(_, _, _) -> Void。
这里您可以找到如何使用try/catch的信息。
https://stackoverflow.com/questions/40732278
复制相似问题