simplexity
simplexity

Reputation: 1557

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?

Upvotes: 2

Views: 1691

Answers (2)

SrB
SrB

Reputation: 363

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?

Upvotes: 1

Talha Q
Talha Q

Reputation: 4360

I would recommend you to use AsyncRequest to fetch and download the image and saved it locally. As you didn't posted any of code of your problem. So i am posting a sample working for me.

Sample for downloading and saving image locally

    var url = NSURL(string : "http://freedwallpaper.com/wp-content/uploads/2014/09/Tattoo-Girl.jpg")

    let urlrequest = NSURLRequest(URL: url!)
    NSURLConnection.sendAsynchronousRequest(urlrequest, queue: NSOperationQueue.mainQueue(), completionHandler: {
        response ,data , error in

        if error != nil
        {
            println("error occurs")
        }
        else
        {
            let image = UIImage(data: data)

            /* Storing image locally */

            var documentsDirectory:String?
            var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
            println(paths)
            if paths.count > 0{
                documentsDirectory = paths[0] as? String
                var savePath = documentsDirectory! + "/bach.jpg"
                NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
                self.bach.image  = UIImage(named: savePath)
            }
        }

    })

}

Upvotes: 2

Related Questions