【发布时间】: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