SNos
SNos

Reputation: 3470

UIImage content of file unexpectedly found nil

I am trying to load an image that I have saved inside Document directory. If I print the path I can see that there is the image however, when I trie to assign the path to a UIImage the app crashes:

static func callSavedProfileImage() -> UIImage{
        //let profilePictureUser = NSUserDefaults.standardUserDefaults()
        let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
        let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask
        let paths            = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)

        var newImage = UIImage!()
        if paths.count > 0
        {
            let dirPath = paths[0]

            let readPath = (dirPath as NSString).stringByAppendingPathComponent("ProfilePic.png")

            print(readPath) ///var/mobile/Containers/Data/Application/C9F738C1-F747-4C1D-ADBE-251F168444D4/Documents/ProfilePic.png

            let savedProfilePicture = readPath

            if let savedImage = UIImage(contentsOfFile: savedProfilePicture) {
                newImage = savedImage
            }

        }


        print(newImage)

        return newImage
    }

Any idea why?

Upvotes: 1

Views: 627

Answers (1)

Eric Aya
Eric Aya

Reputation: 70094

var newImage = UIImage!()

should be

var newImage = UIImage()

When you declare UIImage!() it creates an implicitly unwrapped Optional which will crash if unwrapped while nil.

Just remove the ! to create a normal UIImage, then it won't crash if the image can't be found.

Upvotes: 1

Related Questions