0

thanks for any help upfront.

url session works perfect with connection, it prints the error as nil. but without it it prints the .localizedDescription just fine and shows me the right error, but then continues to do the do{ try } and crashes with this error in the try line:

Thread 6: Fatal error: Unexpectedly found nil while unwrapping an Optional value

now I am not even sure if this has anything to do with the errorhandling. thanks for any help with understanding whats going on or just solving the problem!

func getData(completion: (() -> ())?) {

    let urlString = URL(string: "https://api.coinmarketcap.com/v1/ticker/")

    URLSession.shared.dataTask(with: urlString!, completionHandler: { (data, response                                                                                                         , error) in

        print("before entering do-try-catch", error?.localizedDescription)

        do {

            //create Dictionary
            print("downloading content")

            self.coinData = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]

            //set connection status
            self.connection = true

            //update tableView
            DispatchQueue.main.async {
                completion?()
            }

        } catch {

            print("catch", error.localizedDescription)

            //set connection status
            self.connection = false

            //update tableView
            DispatchQueue.main.async {
                completion?()
            }
        }
    }).resume()
}
2

2 Answers 2

2

Thread 6: Fatal error: Unexpectedly found nil while unwrapping an Optional value is a common problem for beginners.

You try to work with data that is not there. So for example in your code you force to execute try JSONSerialization.jsonObject(with: data!)

When data is nil the code will crash.

The same at the beginning URLSession.shared.dataTask(with: urlString!, completionHandler: { (data, response, error) {}

When urlString is not a valid URL the code will be crash. (In this case the url seems to be valid).

For more information have a look here: https://stackoverflow.com/a/24034551/4420355

Try the following snipped it should work

if let data = data {
 self.coinData = try JSONSerialization.jsonObject(with: data) as? [[String:Any]]
     //... work with coinData
 }
1
  • Okay thank you lot. in what case though would the try do its job and give over to the catch? isnt the idea of the try that if anything behind it (in that line, i think) fails, it cancels the process and gives over to the catch?
    – felixmp
    Commented Feb 23, 2018 at 21:25
1

Reason why it is crashing is because data is Optional and it should be nil or has some value. On line

self.coinData = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]

Compiler thinks:

Let's take a look and unwrap this Optianal variable. But it's nil, there is "nothing"! So what should I unwrap? Let's crash and throw Fatal Error message.

How to easily avoid this with Optional binding:

if let data = data {
....do something with data
} else {
...print error message
}

For more information take look at this brilliant answer. https://stackoverflow.com/a/32170457/3046686

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.