Jab
Jab

Reputation: 27515

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

I want to save and read a UIImage to my temp folder when my app closes and then load and delete it when the app loads. How do I accomplish this. Please help.

Upvotes: 10

Views: 17937

Answers (6)

Milan Nosáľ
Milan Nosáľ

Reputation: 19757

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

Upvotes: 5

Anton
Anton

Reputation: 1223

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

Upvotes: 6

Hardik Thakkar
Hardik Thakkar

Reputation: 15991

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

Upvotes: 2

Zaid Pathan
Zaid Pathan

Reputation: 16820

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
}

Upvotes: 1

ennuikiller
ennuikiller

Reputation: 46985

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;
}

Upvotes: 14

TechZen
TechZen

Reputation: 64428

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.

Upvotes: 3

Related Questions