I'm trying to become familiar with the new do catch
statements with swift 2 and iOS 9
My problem is that when an error occurs with NSURLSession, the data parameter returns nil, and error returns something. In iOS 8 this was expected functionality and we simply used if statements to find out whether or not Data was nil
However with do
catch
, there is the new try
keyword which I thought was meant to see if something works, if it doesn't then default to whatever code is written in catch
However, because data is nil I am getting an unexpected crash. Is this expected functionality, why isn't catch
being called when my try
method fails?
I'm using NSURLSession to pull data from an API.
I create a dataTaskWith request like this:
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
print(request)
print(response)
print(error)
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
Crashes right here because data! is nil.. because there was an NSURLSession error
print(jsonResult)
} catch {
print(error)
}
})
task.resume()
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…