从文档目录加载UIImage

时间:2012-10-24 20:35:14

标签: ios

我正在尝试从文档目录加载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响应的其他方式。

2 个答案:

答案 0 :(得分:9)

要获取文档目录,您应该使用:

NSArray  *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir  = [documentPaths objectAtIndex:0];
NSString  *pngfile = [documentsDir stringByAppendingPathComponent:@"school.png"];

我不太确定你是否还需要附加'MyAppCustomDirectory',但我不这么认为。

答案 1 :(得分:2)

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)