12

我正在尝试UIImage从文档目录加载 a 并将其设置为 a 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 响应的其他方法。

4

2 回答 2

10

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

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

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

于 2012-10-24T20:40:33.433 回答
5

斯威夫特 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)
于 2017-11-23T16:55:55.587 回答