0
votes

IOS swift problem while unwrapping, crashing. I am getting data as NSData, when I am printing in string or

var dict : AnyObject = NSJSONSerialization.JSONObjectWithData(returnData!, options: NSJSONReadingOptions(0), error: &respError) as AnyObject!

doing this its returning dict nil, or

var datastring : NSString = NSString(data:returnData!, encoding:NSUTF8StringEncoding)[This is My Image Liknk] as! String

datastring causing fatal error:

unexpectedly found nil while unwrapping an Optional value.

3

3 Answers

1
votes

You are unwrapping the values forcefully (Forced Unwrapping), If that object contains nil then it will generate runtime error.

Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

0
votes

You would do well to check all your values before you assume they're not nil. With the "!" you tell your code that this value can be safely unwrapped even though it may still be nil. Hence when it is nil, it crashes. What I usually do is:

// Unwrap the string, check if it ain't nil and store this in a new value.
if let content: String = item.content as? String {
    if content != "" {
        var error: NSError?
        // Unwrap the data optional from dataUsingEncoding and also check if it ain't nil. Store this in a new value.
        if let data: NSData = content.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true),
            // Unwrap the optional returned from JSONObjectWithData and also check if it ain't nil. Store the value in a new object.
            let json: NSMutableDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSMutableDictionary {
            // Do stuff with the dictionary.
        } else {
            if let err: NSError = error {
                println(err.localizedDescription)
            }
        }
    }
}

With all these checks I am sure my code will not crash deserializing the string to json in swift.

It appears I was a bit slow with my answer but Nilesh Patel has a good quote there which you should look at.

0
votes

It is because returnData! is nil. If you put a break point at var dict, run and then po returnData! I believe you will find that to be true. And because the data at which NSJSONSerialization is trying to accept as a parameter is nil, it will be as well. I would go through your logic or your source to figure out why it is nil.

Also if you are using NSURLSession to retrieve your data - make sure you have a valid configured session before calling dataTaskWithURL. Like so...

var config = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: config)
var dataTask:NSURLSessionDataTask = session.dataTaskWithURL...

I ran into this problem and figured out that the session needed to be configured before I called the data task.

EDIT Also try this. Use optional binding.

if let data: NSDictionary = NSJSONSerialization.JSONObjectWithData(returnData, options: NSJSONReadingOptions.AllowFragments, error: nil) as? NSDictionary {

            println("json = \(data)")
        }

        else { 

            println("returnData really is nil")
        }