【问题标题】:Saving image to documents directory with overwrite使用覆盖将图像保存到文档目录
【发布时间】:2019-04-15 16:50:37
【问题描述】:

我正在使用设备相机拍摄照片并将其以特定文件名保存到 Documents 目录中。但是,如果已存在同名文件,则不会保存该文件。我怎样才能简单地覆盖同名文件,或者如果它确实存在,先删除它?我更喜欢第一个选项。

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

【问题讨论】:

    标签: swift photo nsfilemanager


    【解决方案1】:

    write(to 默认覆盖数据,但通过检查文件是否存在来阻止它。

    只需删除检查

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多