Search code examples
swiftnsurlconnection

swift nsurlconnection fatal error: unexpectedly found nil while unwrapping an Optional value



I am using the following piece of code to download
some xml data from my server

//Build & Request the Url
let url = NSURL(string: "http://sample.com")
let request: NSURLRequest  = NSURLRequest(URL: url!)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?
>=nil
var error: NSErrorPointer = nil
var xmlData: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)!
var err: NSError

It works as expected most of the time. But if I disconnect the internet and close the app and open again when the internet is connected it throws the fatal error

var xmlData: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)!

This seems to be the "faulty" line. Since this happens only after I disconnect/reconnect the internet
maybe I should refresh dhe NSURLCONNECTION or something, I don't know.
I am thinking this because since it works as expected most of the time
maybe after I disconnect the NSURLCONNECTION doesn't properly detect
that the device is reconnected.

Any help/suggestions would be highly appreciated.
Thank you.


Solution

  • You should use question optional mark, because it can be nil

    var xmlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)
    

    or

    var xmlData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)?
    

    or

    var xmlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil) as? NSData