I need to capture image from image picker controller and save image with its custom name and later on fetch all the images with their respective names .
Asked
Active
Viewed 864 times
2 Answers
0
try this
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/MyImageName.png"
// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)```

Amit Samant
- 13,257
- 2
- 10
- 16
0
I assume you already have the picker working in order to get an image from the gallery, and only wants to save and get it from the app folder.
I was able to make this with the following code:
Class ImagePersistance.swift
open class ImagePersistance: NSObject {
var fileManager: FileManager
var documentsURL: URL
var documentPath: String
public override init() {
self.fileManager = FileManager.default
self.documentsURL = self.fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
self.documentPath = documentsURL.path
}
public func saveImage(image: UIImage?, name: String) throws {
if image != nil {
let filePath = documentsURL.appendingPathComponent("\(String(name)).png")
if let currentImage = image {
if let pngImageData = UIImagePNGRepresentation(currentImage) {
try pngImageData.write(to: filePath, options: .atomic)
}
}
}
}
public func getImage(name: String) -> UIImage? {
let filePath = documentsURL.appendingPathComponent("\(String(name)).png")
if FileManager.default.fileExists(atPath: filePath.path) {
if let image = UIImage(contentsOfFile: filePath.path) {
return image
}
}
return nil
}
}
How to use it:
Save image:
do {
try ImagePersistance().saveImage(image: IMAGE_HERE, name: "IMAGE_NAME")
catch {
print("image error")
}
Get saved image
let image:UIImage = ImagePersistance().getImage(name: "IMAGE_NAME")

alxlives
- 5,084
- 4
- 28
- 50