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