URLSession 和 JSONSerialization Swift 3

URLSession & JSONSerialization Swift 3

在您阅读本文之前,请理解我是 Swift 的初学者,我正在努力学习。我浏览了一些网站,希望得到答案,但我要么找不到,要么做错了。我一直在关注本教程,但这是旧的,没有更新 >>Tutorial I followed<<

我也尝试将一些修改为 swift 3 - 虽然我可能没有做对。

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

invalid conversion from throwing function of type'(_, _, _) throws -> Void' to non-throwing function type

对于下面这一行:

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

和变量 "jsonDict" - 我收到错误

extra arg 'error' in call.

提前致谢

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

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

Here 您可以找到有关如何使用 try/catch.

的信息

请查找 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

的参数