Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage returns nil but exists

Tags:

ios

swift

uiimage

I have a problem in Swift. I try to load an image which is stored in the DocumentsDirectory but it returns nil.

Here is the code:

if NSFileManager.defaultManager().fileExistsAtPath(url!.path!) {
    //show image
    print("Image " + key + " exists")
    if let image =  UIImage(contentsOfFile: url!.path!){
        return image
    }
    else {
        print("error image")
        return nil
    }
}

I always got "error image" but the file exists. I don't understand the problem.

Thanks,

Henry

like image 379
user3900157 Avatar asked Dec 13 '25 14:12

user3900157


1 Answers

I have rewritten your code into it's own function so you can test it with out having to change to your code too much. It works ok for me which leads me to suspect that your path is not set correctly or your code is failing to create an image from the file it accesses via the path you supply. The function below will tell you if the file does not exist or in UIImage failed to create the image.

You need to isolate where the error is occurring and start from there.

func getImage(url: NSURL) -> UIImage? {

    var image : UIImage?

    if let path = url.path {
        if FileManager.default.fileExists(atPath: path) {
            if let newImage = UIImage(contentsOfFile: path)  {
                image = newImage
            } else {
                print("getImage() [Warning: file exists at \(path) :: Unable to create image]")
            }

        } else {
            print("getImage() [Warning: file does not exist at \(path)]")
        }
    }

    return image
}
like image 92
Peter Hornsby Avatar answered Dec 15 '25 03:12

Peter Hornsby