Reputation: 13178
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.
Upvotes: 12
Views: 6825
Reputation: 2468
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)
Upvotes: 5
Reputation: 5519
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.
Upvotes: 10