-2

I'm new to Swift...

Trying to display some API data from newsapi which was working fine, but after a few runs I started getting the

Fatal error: Unexpectedly found nil while unwrapping an Optional value error at line 12 (let articles = dataDictionary["results"] as! [[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()
}

Any ideas?

Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
Modulus
  • 13
  • 1
  • 4

2 Answers2

1

Your dataDictionary does not contain key like results. It has articles key value. So dataDictionary["results"] is a null object.

dataDictionary["results"] will be null so try using ? instead of !

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

I think it will be

let articles = dataDictionary["articles"] as? [[String: Any]]
Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
1

Use guard let on this change:-

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

to this line:-

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

don't use ! until you sure this must have value

Also see this answer to avoid this !:- Guard not unwrapping optional

Wings
  • 2,398
  • 23
  • 46