1
votes

I am using Swift 4, and I need to know how to delete using UIDocument. I know how to set up the url path:

if let url = try? FileManager.default.url(
        for: .documentDirectory,
        in: .userDomainMask,
        appropriateFor: nil,
        create: true
        ).appendingPathComponent("Inbox/test.txt") {
        falloutFileHandler = FalloutTextFileHandler(fileURL: url)
    }

where falloutFileHandler is of type UIDocument, and falloutFileHandler has a property called falloutFile which stores the string as a property called 'data'.

And I know how to open the file:

falloutFileHandler?.open { success in
        if success {
            if let theText = self.falloutFileHandler?.falloutFile?.data {
                self.textView.text = self.text!
            } else {
                print("Something went wrong")
            }
        }
    }

But I do not know how to delete a file using UIDocument. Thank you in advance.

Also, is there a way to print out why something isn't successful in opening? Such as print(error) or something like that instead of doing what I did which was print("Something went wrong")?

1

1 Answers

3
votes

UIDocument is used as the underlying container for an iOS app's documents. It knows how to read a document, revert a document, compare versions of a document (e.g. where your local document might be different than what's stored in iCloud, etc.).

You can't use UIDocument's built-in API's to delete itself, though. You'd either have to implement in your subclass (because only your subclass knows exactly where/how your document is stored) or you'd most likely need to use FileManager, just like how you used it to choose where to initially load/read your UIDocument (or in your case FalloutTextFileHandler) from.

To use the latter, you'd do something like:

do {
    let fm = FileManager.default
    if let url = try fm.url(
        for: .documentDirectory,
        in: .userDomainMask,
        appropriateFor: nil,
        create: true
        ).appendingPathComponent("Inbox/test.txt") {

            // the actual delete method
            try FileManager.default.removeItem(at: url)

        }
    } catch let error as NSError {
        print("Ooops! Something went wrong: \(error)")
    }

}