DanTdd
DanTdd

Reputation: 342

Unexpectedly found nil while unwrapping an Optional value when using json API result and NSDictionary

I am trying to use an API to get json data every 0.5 seconds. The API allows thousands of requests per second however sometimes when running the application, I get this crash:

fatal error: unexpectedly found nil while unwrapping an Optional value

This is the code I am using to get the json data.

    var url : String = "URL.COM" 
    var request : NSMutableURLRequest = NSMutableURLRequest

    request.URL = NSURL(string: url)
    request.HTTPMethod = "GET"

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse?, data: NSData?, error: NSError?) -> Void in
        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary

Can anyone advise me how to prevent this? I understand why the data might be nil occasionally but I want the program to keep checking regardless of if it is nil or not, as it will soon be something other than nil.

Upvotes: 0

Views: 609

Answers (2)

Diego Freniche
Diego Freniche

Reputation: 5414

The problem lays in data. It can be nil, but you're unwrapping it using !, which means: "I know there's some data inside here, unwrap it". The problem is when there's no data.

To solve it, use this pattern in Swift:

if let myData = data {
// do something using myData. If data is nil, doen't even enter here
}

Complete code:

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse?, data: NSData?, error: NSError?) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    if let myData = data {

    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(myData, options:NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
    }
})

Upvotes: 0

Dejan Skledar
Dejan Skledar

Reputation: 11435

You should add this, before the sterilization:

if data == nil 
{
   println("data is nil")
   return
}

Upvotes: 1

Related Questions