【问题标题】:URLSession & JSONSerialization Swift 3URLSession & JSONSerialization Swift 3
【发布时间】:2017-04-05 13:30:26
【问题描述】:

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

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

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

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

对于下面这一行:

让任务:URLSessionDataTask = session.dataTask(with: request, completionHandler: {data, response, error -> Void in

对于变量“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()
}

【问题讨论】:

  • 它应该是 var jsonDict = try JSONSerialization.JSONObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as NSDictionary ,在 swift 3 错误参数中删除
  • @Vinodh - 谢谢,我没想到会这么简单。
  • 将其发布为对其他人有帮助的答案
  • 尚未完全完成 - URLSessionDataTask 仍有问题
  • 给点时间我会修复上面的代码并给你答案

标签: ios swift3 urlsession


【解决方案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 的参数

【讨论】:

  • 似乎解决了它,我想。谢谢!当你的意思是 URL 的参数时......像这样? /http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN ("AAPL","GOOG","FB")&format=json&env=http://datatables.org/alltables.env
  • 是的,你是对的,我不知道你在“stringQuotes”中传递了什么,现在你在评论中提到了。谢谢
  • 我添加的url编码方法的另一个更改应该是urlFragmentAllowed而不是urlHostAllowed,如果我使用urlHostAllowed我无法访问yahoo api
【解决方案2】:

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

Here你可以找到如何使用try/catch的信息。

【讨论】:

  • 我尝试过,但一直出错,这就是我在这里寻求帮助的原因。 URLSession 的原始代码是这个 let 任务: NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
  • 为我解决了这个问题 `do{ var josnDict = try JSONSer... ... }) } catch { //handle error } `
猜你喜欢
  • 2017-06-22
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多