致命错误:在用API数据解开Optional值时意外发现nil

时间:2018-11-28 09:33:01

标签: swift api

我是Swift的新手...

尝试显示来自newsapi的一些API数据,效果很好,但运行几次后,我开始获取

  

致命错误:在第12行解开可选值错误时意外发现nil(让条款= dataDictionary [“ results”]为[[String:Any]])

    let url = URL(string: "https://newsapi.org/v2/everything?sources=techcrunch&apiKey=d65fb8f01d8e42c7b106590d09149d39")!

    let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
    let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
    let task = session.dataTask(with: request) { (data, response, error) in

         //This will run when the network request returns
        if let error = error {
            print(error.localizedDescription)
        } else if let data = data {
            let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            let articles = dataDictionary["results"] as! [[String: Any]]
            self.articles = articles
            self.tableView.reloadData()
            }
        }
    task.resume()
}

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您的dataDictionary不包含results之类的密钥。它具有articles键值。因此dataDictionary["results"]是一个空对象。

dataDictionary["results"]将为空,因此请尝试使用?而非!

let articles = dataDictionary["results"] as? [[String: Any]]

我想将会是

let articles = dataDictionary["articles"] as? [[String: Any]]

答案 1 :(得分:1)

对此更改使用警戒线:-

let articles = dataDictionary["results"] as! [[String: Any]]

此行:-

guard  let articles = dataDictionary["results"] as? [[String: Any]] else { return}

在确定必须具有值之前不要使用!

也请参阅此答案以避免此!:-Guard not unwrapping optional