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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With