Search code examples
iosswifttry-catchnsjsonserialization

Try and catch is not throwing message and handling the issue


I am trying to post something to my API regularly in my app lets say every 3 minutes and in return I some data sometimes, data does not get delivered and I found the data nil, that's why I tried to put a try/catch concept with below code:

        var err: NSError?
        var json:NSDictionary!
        do {
            json =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
        }
        catch {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                postCompleted(succeeded: false, msg: "Logged in.")

            })
        }

However catch statement never get to work and each time I get nil, app crash inside do.


Solution

  • public class func JSONObjectWithData(data: NSData, options opt: NSJSONReadingOptions) throws -> AnyObject

    Because data: NSData is not unwrapped. if data is nil, function will be crash. You add

    guard let data = data else { return }

    And try/catch Because this function may throws error. If data encoding format is incorrect,this function will throws error,you can catch in catch.

    hopefully it will be useful to you.