1

在您阅读本文之前,请了解我在某种程度上是 Swift 的初学者,并且正在努力学习。我浏览了一些网站希望得到答案,但我找不到或做错了。我一直在关注这个教程,但这是旧的,没有更新>>我遵循的教程<<

我还尝试将一些修改为 swift 3 - 尽管我可能做得不对。

我如何正确地正确执行 URLSession?我收到此错误:

从类型为'(_, _, _) throws -> Void' 的抛出函数到非抛出函数类型的无效转换

对于下面的这一行:

let task : URLSessionDataTask = session.dataTask(with: request, completionHandler: {data, response, error -> Void in

对于变量“jsonDict”-我收到错误

调用中的额外参数“错误”。

提前致谢

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()
}
4

2 回答 2

1

请找到 Swift 3.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-22T02:34:43.690 回答
0

你的问题不在URLSessionDataTask你的completionHandler. 更具体地说是var jsonDict = try JSONSerialization...位。try表示您的代码可以抛出异常但您不处理它 ( catch)。这就是为什么编译器决定你的完成处理程序是(_, _, _) throws -> VoidwhiledataTask方法期望的类型(_, _, _) -> Void

在这里您可以找到如何使用的信息try/catch

于 2016-11-22T02:16:03.433 回答