Ios 从文档目录加载UIImage
我正在尝试从文档目录加载Ios 从文档目录加载UIImage,ios,Ios,我正在尝试从文档目录加载UIImage,并将其设置为UIImageView,如下所示: NSString *pngfile = [[MyUtil getLocalDirectory] stringByAppendingPathComponent:@"school.png"]; NSLog(@"%@", pngfile); if ([[NSFileManager defaultManager] fileExistsAtPath:pngfile]) { NSData *imageData
UIImage
,并将其设置为UIImageView
,如下所示:
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];
}
但是,每当我尝试上述操作时,图像都不会加载。图像位于Documents/MyAppCustomDirectory/school.png
中。从该目录加载上述内容是否正确
我还尝试了其他几种方法:
UIImage imageWithContentsOfFile
,以及基于SO响应的其他方法。要获取文档目录,您应该使用:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *pngfile = [documentsDir stringByAppendingPathComponent:@"school.png"];
我不太确定您是否还需要附加“MyAppCustomDirectory”,但我不这么认为。Swift 4解决方案:
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)
显示
MyUtil getLocalDirectory
的代码。