UIImage Download Returning nil and Crashing App (Swift)


I have an image url string:

var remoteImage: String = "http://server.com/wall-e.jpg"

I then construct a UIImage to download on a separate thread using Grand Central Dispatch with remoteImage as the NSURL string parameter:

let getImage = UIImage(data: NSData(contentsOfURL: NSURL(string: remoteImage)!)!)

When it is finished and I return back to the main thread, I have it save internally:

UIImageJPEGRepresentation(getImage, 1.0).writeToFile(imagePath, atomically: true)

On Wi-fi and LTE it downloads fine, but when testing edge cases such as on an Edge network (no pun intended), I inconsistently get the error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Now I thought I would be safe by making sure that it wasn't nil by adding in:

if getImage != nil { ... }

But it didn't seem to make a difference. It still gets the error and highlights the let getImage as written above. What am I doing wrong here? Should I be checking nil in a different manner or method?


The error, does, in fact lie on the line:

    let getImage = UIImage(data: NSData(contentsOfURL: NSURL(string: remoteImage)!)!)

The reason is that it's not the UIImage that is initially returning nil, it is probably NSData returning nil. You could check if NSData is returning nil, and then create the UIImage object instead.

EDIT: What the particular line of code is doing is it is assuming that NSData is always returning a non-nil value, which may not be true when you are not connected. When you're not connected, it gets a nil value, which you are trying to say will never be a nil value using the exclamation mark (!).

I suggest you read further on how Swift works. For this particular example, take a look at what the exclamation marks actually mean in Swift: What does an exclamation mark mean in the Swift language?

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment