Using FileManager it is possible to check if a file exists using the FileManager
method fileExists(atPath:)
when saving files to the App Sandbox.
However, when working directly with UIDocument
the saving method save(to:for:completion)
can accept a new URL which overwrites whatever might have been there with no warning, making it easy to accidentally overwrite a file. In fact, as far as I know, none of the UIDocument methods communicate details about why a document operation may have failed.
Is this type of check only possible with FileManager or some other framework?
1. Define Document Subclass
class TextDocument: UIDocument {
var text: String?
}
2. Get URL of documents directory
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first!
3. Create 2 documents and save
let doc1 = TextDocument(fileURL: documentsDirectory
.appendingPathComponent("File 1")
.appendingPathExtension("txt"))
let doc2 = TextDocument(fileURL: documentsDirectory
.appendingPathComponent("File 2")
.appendingPathExtension("txt"))
doc1.save(to: doc1.fileURL, for: .forCreating) { success in
print(success) // prints true
}
doc2.save(to: doc2.fileURL, for: .forCreating) { success in
print(success) // prints true
}
4. Problem: Saving doc1 to doc2's URL overwrites doc2 without warning.
doc1.save(to: doc2.fileURL, for: .forOverwriting) { success in
print(success) // prints true
}