I'm trying to load a UIImage
from the documents directory and set it to a UIImageView
as per below:
NSString *pngfile = [[MyUtil getLocalDirectory] stringByAppendingPathComponent:@"school.png"];
NSLog(@"%@", pngfile);
if ([[NSFileManager defaultManager] fileExistsAtPath:pngfile]) {
NSData *imageData = [NSData dataWithContentsOfFile:pngfile];
UIImage *img = [UIImage imageWithData:imageData];
[schoolImage setImage:img];
}
However, whenever I try the above, the image never loads. The image is in Documents/MyAppCustomDirectory/school.png
. Is the above correct to load from that directory?
I also tried a few others: UIImage imageWithContentsOfFile
, among other ways based on SO responses.
The Documents directory is a better place to store data. We could append Documents to the path returned by the NSHomeDirectory() function, but it's a better idea to ask the FileManager class for the location of the Documents directory. This is slightly more verbose.
To write the image data to the Documents directory, we invoke the write(to:) method on the Data object. Because the write(to:) method is throwing, we wrap the method call in a do-catch statement and prefix it with the try keyword.
An object that manages image data in your app.
To get the documents directory you should use:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *pngfile = [documentsDir stringByAppendingPathComponent:@"school.png"];
I'm not quite sure if you also need to append the 'MyAppCustomDirectory', but I don't think so.
Swift 4 Solution:
guard let documentsDirectory = try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor:nil,
create:false)
else {
// May never happen
print ("No Document directory Error")
return nil
}
// Construct your Path from device Documents Directory
var imagesDirectory = documentsDirectory
// Only if your images are un a subdirectory named 'images'
imagesDirectory.appendPathComponent("images", isDirectory: true)
// Add your file name to path
imagesDirectory.appendPathComponent("school.png")
// Create your UIImage?
let result = UIImage(contentsOfFile: imagesDirectory.path)
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