开发者

How do I save and read an image to my temp folder when quitting and loading my app

开发者 https://www.devze.com 2022-12-14 16:17 出处:网络
I want to save and read a UIImage to my temp folder when my app closes and then load and delete it when the a开发者_开发技巧pp loads. How do I accomplish this. Please help.These methods allow you to s

I want to save and read a UIImage to my temp folder when my app closes and then load and delete it when the a开发者_开发技巧pp loads. How do I accomplish this. Please help.


These methods allow you to save and retrieve an image from the documents directory on the 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;
}


Swift 3 xCode 8.2

Documents directory obtaining:

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

Saving:

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
}

Loading:

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

Example:

//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")
}


Swift 4 implementation:

// saves an image, if save is successful, returns its URL on local storage, otherwise returns nil
func saveImage(_ image: UIImage, name: String) -> URL? {
    guard let imageData = image.jpegData(compressionQuality: 1) else {
        return nil
    }
    do {
        let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name)
        try imageData.write(to: imageURL)
        return imageURL
    } catch {
        return nil
    }
}

// returns an image if there is one with the given name, otherwise returns nil
func loadImage(withName name: String) -> UIImage? {
    let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name)
    return UIImage(contentsOfFile: imageURL.path)
}

Usage example (assuming we have an image):

let image = UIImage(named: "milan")

let url = saveImage(image, name: "savedMilan.jpg")
print(">>> URL of saved image: \(url)")

let reloadedImage = loadImage(withName: "savedMilan.jpg")
print(">>> Reloaded image: \(reloadedImage)")


In addition, you don't ever want to save anything into the actual tmp directory that you want around after the app shuts down. The tmp directory can be purged by the system. By definition, it exist solely to hold minor files needed only when the app is running.

Files you want to preserve should always go into the documents directory.


Tested Code for swift

//to get document directory path
    func getDocumentDirectoryPath() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }

Call using

if let data = UIImagePNGRepresentation(img) {
     let filename = self.getDocumentDirectoryPath().stringByAppendingPathComponent("resizeImage.png")
     data.writeToFile(filename, atomically: true)
}


The Untested Swift tweak for selected answer:

class func saveImage(image: UIImage, withName name: String) {
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    var data: NSData = UIImageJPEGRepresentation(image, 1.0)!
    var fileManager: NSFileManager = NSFileManager.defaultManager()

    let fullPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name)
    fileManager.createFileAtPath(fullPath.absoluteString, contents: data, attributes: nil)
}

class func loadImage(name: String) -> UIImage {
    var fullPath: String = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name).absoluteString
    var img:UIImage = UIImage(contentsOfFile: fullPath)!
    return img
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号