Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

nsurlsession - Swift 2 iOS 9 Do Catch Try crashing with unexpected nil found

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because catch only catches what a functions "throws".

NSJSONSerialization throws, but force unwrapping an empty Optional doesn't, it always crashes.

Use if let or the new guard function to safely unwrap your values.

do {
    if let myData = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(myData, options: []) as? NSDictionary {
        print(jsonResult)
    }
} catch {
    print(error)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...