退出并加载我的应用程序时,如何将图像保存并读取到临时文件夹

Jab*_*Jab 9 iphone save uiimage

当我的应用程序关闭时,我想保存并读取我的临时文件夹的UIImage,然后在应用程序加载时加载并删除它.我该如何做到这一点.请帮忙.

enn*_*ler 12

这些方法允许您从iphone上的文档目录中保存和检索图像

+ (void)saveImage:(UIImage *)image withName:(NSString *)name {
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
    [fileManager createFileAtPath:fullPath contents:data attributes:nil];
}

+ (UIImage *)loadImage:(NSString *)name {
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];    
    UIImage *img = [UIImage imageWithContentsOfFile:fullPath];

    return img;
}
Run Code Online (Sandbox Code Playgroud)

  • DocumentsDirectory来自哪里? (5认同)
  • 有关文档目录的详细信息,请访问http://stackoverflow.com/questions/6907381/what-is-the-documents-directory-nsdocumentdirectory/6907432#6907432 (2认同)

Ant*_*ton 5

斯威夫特 3 xCode 8.2

文档目录获取:

func getDocumentDirectoryPath() -> NSString {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory as NSString
}
Run Code Online (Sandbox Code Playgroud)

保存:

func saveImageToDocumentsDirectory(image: UIImage, withName: String) -> String? {
    if let data = UIImagePNGRepresentation(image) {
        let dirPath = getDocumentDirectoryPath()
        let imageFileUrl = URL(fileURLWithPath: dirPath.appendingPathComponent(withName) as String)
        do {
            try data.write(to: imageFileUrl)
            print("Successfully saved image at path: \(imageFileUrl)")
            return imageFileUrl.absoluteString
        } catch {
            print("Error saving image: \(error)")
        }
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

加载:

func loadImageFromDocumentsDirectory(imageName: String) -> UIImage? {
    let tempDirPath = getDocumentDirectoryPath()
    let imageFilePath = tempDirPath.appendingPathComponent(imageName)
    return UIImage(contentsOfFile:imageFilePath)
}
Run Code Online (Sandbox Code Playgroud)

例子:

//TODO: pass your image to the actual method call here:
let pathToSavedImage = saveImageToDocumentsDirectory(image: imageToSave, withName: "imageName.png")
if (pathToSavedImage == nil) {
    print("Failed to save image")
}

let image = loadImageFromDocumentsDirectory(imageName: "imageName.png")
if image == nil {
    print ("Failed to load image")
}
Run Code Online (Sandbox Code Playgroud)