priyanka gautam
priyanka gautam

Reputation: 377

Crash without Internet

I am getting error

fatal error: unexpectedly found nil while unwrapping an Optional value

on this line when Internet is not connected.

let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary            // Line 


                self.dict = jsonData;

                self.array1 = (self.dict.objectForKey("results") as? NSMutableArray)!

                dispatch_async(dispatch_get_main_queue()) {
                    self.table.reloadData()
                }


            } catch {

                print(error)
            }
        })
        task1.resume()

Please help Any help would be apperciated

Upvotes: 1

Views: 404

Answers (1)

Dejan Skledar
Dejan Skledar

Reputation: 11435

This happens, because you force unwrap the data, which is always a bad idea, because you don't know if its nil or not.

To get around this, you need to check if data is nil, before you try serial the JSON:

// Checking if data is nil, and unwraping it
if let unwrappedData = data {
    let jsonData = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: .MutableContainers) as! NSDictionary 
    // handle json here
}

or another way:

if data == nil {
    return 
}
// else, data is not nil
let jsonData = try NSJSONSerialization...

Upvotes: 4

Related Questions