I get the error "Fatal error: Unexpectedly found nil while unwrapping an optional value". I am trying to fetch JSON as a dictionary from my server. How do I throw the error if the data is nil?
let jsonUrl = "jsonurl"
let session = NSURLSession.sharedSession()
let shotsUrl = NSURL(string: jsonUrl)
let task = session.dataTaskWithURL(shotsUrl!, completionHandler: {
(data,response,error) -> Void in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) // Get error
dispatch_async(dispatch_get_main_queue()) {
for newData in json as! [Dictionary<String, AnyObject>] {
// do stuff
}
}
} catch {
}
})
task.resume()
Edit: to clarify, I am testing when there is no internet connection, it should ignore the error thrown, instead it gives an error. I tried
guard let data = data else { return }
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
but it says "Cannot force unwrap of optional type 'NSData'" on the let json line