Search code examples
swiftphotonsfilemanager

Saving image to documents directory with overwrite


I am capturing a photo with the device camera and saving it to the Documents directory with a specific filename. However, if a file of the same name already exists then the file is not saved. How can I simply overwrite a file of the same name, or if it does exist, delete it first? I'd prefer the first option.

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

// Create the destination file URL for saving
let fileURL = documentsDirectory.appendingPathComponent(photoFilename)

if let data = image.jpegData(compressionQuality: 1.0),
    !FileManager.default.fileExists(atPath: fileURL.path) {
    do {
        // Write the image data
        try data.write(to: fileURL)
    } catch {
        let alert = UIAlertController(title: "OOPS!", message: "Couldnt save the image!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.present(alert, animated: true)
    }
}
print("not saved")

Solution

  • write(to overwrites data by default but you prevent it by checking if the file exists.

    Just remove the check

    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    
    // Create the destination file URL for saving
    let fileURL = documentsDirectory.appendingPathComponent(photoFilename)
    
    if let data = image.jpegData(compressionQuality: 1.0) {
        do {
            // Write the image data
            try data.write(to: fileURL)
        } catch {
            let alert = UIAlertController(title: "OOPS!", message: "Couldnt save the image!", preferredStyle: .alert)
             alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
             self.present(alert, animated: true)
        }
    } else {
        print("not saved")
    }