Save & Load Image From Documents Directory in Swift

It’s a common requirement in Apps that we need to save images in the phone’s storage. For example, you download an image from your server and want to save it for future use. In IOS you can use Documents Directory for that purpose. Documents Directory is a slice of storage dedicated to each App where we can store some data. No App can delete the content of other Apps from its Documents Directory. The following methods will help you to save & load image from Documents Directory in Swift.

Save Image in Documents Directory

public static func saveImageInDocumentDirectory(image: UIImage, fileName: String) -> URL? {
        
        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
        let fileURL = documentsUrl.appendingPathComponent(fileName)
        if let imageData = UIImagePNGRepresentation(image) {
            try? imageData.write(to: fileURL, options: .atomic)
            return fileURL
        }
        return nil
    }

This method takes UIImage and the file name as a parameter. It will save your image with your specified file name in Documents Directory and will return you Its File URL for reference.

Load Image from Documents Directory

public static func loadImageFromDocumentDirectory(fileName: String) -> UIImage? {
        
        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
        let fileURL = documentsUrl.appendingPathComponent(fileName)
        do {
            let imageData = try Data(contentsOf: fileURL)
            return UIImage(data: imageData)
        } catch {}
        return nil
    }

This function takes the file name as a parameter and returns the UIImage you previously saved in Documents Directory.

That’s it. This is how you can save & load image From Documents Directory. At the following link, you can find many other helping tutorials.
Handy Opinion Tutorials

Please share this post:
RSS
Follow by Email
Facebook
Twitter
LinkedIn
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.