Search code examples
objective-ciphoneswiftafnetworking-2

Unwrapping an Optional value error in Swift


According to the question subject it is very frequent question and lot many answers there on stacks but i am confuse with behaviour of the error assurance cases. I am little new to Swift and i have some codes. In this code some times i getting and error of Unwrapping an Optional value

Bellow is the code

let operation = AFHTTPRequestOperation(request: request)
operation.setCompletionBlockWithSuccess({ (operation:AFHTTPRequestOperation!, responseObject:AnyObject!) -> Void in
var error:NSError?

//Bellow line gives me an error
let responseDict = NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options:NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

Note: This line gives me and error only when my internet connectivity is down. When internet is totally disconnect then this error not comes up and it goes to Error block of AFNetworking. And when internet is fully working then also i did not get this error as well.

Please suggest some modification or replacement in code.


Solution

  • Your responseDict might not be valid JSON in this case. Whenever you get an error like this, look carefully at all your forced unwrapped optionals. In this case:

    let responseDict = NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options:NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
    

    Instead use:

    if let responseDict = NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options:NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary {
        // Response was valid JSON
    }