1

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
}
MH175
  • 2,234
  • 1
  • 19
  • 35
  • You are using `FileManager`. Why don't you want to use `fileExists(atPath:)`? – Willeke Aug 31 '21 at 05:15
  • Apple's documentation recommends against it. Also I'm trying learn. iOS FileIO seems to have functionality scattered around and I'm trying to see what dependencies I may need and the behavior of each. For example, on `Data` there is `write(to:options)` which has an in-built option for preventing overwriting files, yet this option seems to be lacking on `UIDocument`. – MH175 Aug 31 '21 at 15:24

0 Answers0