URLSession& JSONSerialization Swift 3

时间:2016-11-22 01:17:07

标签: ios swift3 urlsession

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

我也尝试将一些修改为swift 3 - 尽管我可能没有做好。

我如何正确地完成URLSession?我收到这个错误:

  

投掷函数的无效转换'(_,_,_)throws - >   虚空'到非投掷函数类型

以下这一行:

  

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

和变量" 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()
}

2 个答案:

答案 0 :(得分: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

的参数

答案 1 :(得分:0)

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

Here您可以找到有关如何使用(_, _, _) -> Void的信息。