从文档目录加载UIImage

我想从文档目录中加载一个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解决scheme:

 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)