我正在使用设备相机拍摄照片,并将其保存到具有特定文件名的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")
答案 0 :(得分:0)
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")
}