UIDocumentBrowserViewController create new document used to work, but...

is now broken. (but definitely worked when I originally wrote my Document-based app) It's been a few years.

DocumentBrowserViewController's delegate implements the following func.

    func documentBrowser(_ controller: UIDocumentBrowserViewController, didRequestDocumentCreationWithHandler importHandler: @escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) {
        
        let newDocumentURL: URL? = Bundle.main.url(forResource: "blankFile", withExtension: "trtl2")

        // Make sure the importHandler is always called, even if the user cancels the creation request.
        if newDocumentURL != nil {
            importHandler(newDocumentURL, .copy)
        } else {
            importHandler(nil, .none)
        }
    }

When I tap the + in the DocumentBrowserView, the above delegate func is called (my breakpoint gets hit and I can step through the code) newDocumentURL is getting defined successfully and importHandler(newDocumentURL, .copy)

gets called, but returns the following error:

Optional(Error Domain=com.apple.DocumentManager Code=2 "No location available to save “blankFile.trtl2”." UserInfo={NSLocalizedDescription=No location available to save “blankFile.trtl2”., NSLocalizedRecoverySuggestion=Enable at least one location to be able to save documents.})

This feels like something new I need to set up in the plist, but so far haven't been able to discover what it is.

perhaps I need to update something in info.plist? perhaps one of:

  • CFBundleDocumentTypes
  • UTExportedTypeDeclarations

Any guidance appreciated. thanks :-)

According to the step 2 of the doc you need to save the new document to a temporary location first.

Try something like this:

if let newDocumentURL = newDocumentURL,
   let appropritateURL = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false),
   let newDocumentTempURL = try? FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: appropritateURL, create: true).appendingPathComponent(newDocumentURL.lastPathComponent) {
  try! FileManager.default.copyItem(at: newDocumentURL, to: newDocumentTempURL)
  importHandler(newDocumentTempURL, .copy)
}

Btw, the doc's sample project also stopped to work for it creates a new document the same way. But with the above changes it starts to work.

UIDocumentBrowserViewController create new document used to work, but...
 
 
Q