Search code examples
macosmac-catalystuidocumentpickerviewcontroller

Why is UIDocumentPickerViewController working on iOS, but showing the wrong folder on Mac Catalyst?


The code below works fine on an iPad or iPhone -- saveDocument() (see below) writes to /Users/me/Library/Containers/My-App/Data/Documents, and openDocument() shows me the content of that folder.

On macOS, however, openDocument() shows the Documents folder at the root level of iCloud Drive, not the sandboxed version, which is local to my computer

It's like the documentPickerVC.directoryURL is being ignored. Why is that?

If it helps, the documentURL looks like this:

file:///Users/me/Library/Containers/org.me.My-App/Data/Documents/

Any help would be really, really appreciated!

func saveDocument(){
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    do {
        let puzzleData = try? encoder.encode(puzzle)
        print("Saving: \(documentURL)")
        let saveableURL = documentURL!.appendingPathComponent("\( .puzzle.date)")
        try puzzleData!.write(to: saveableURL)
    } catch {
        displayError(title: "Error while saving document", message: "There was an error: \(error)")
    }
}
    // when the user taps on the Open button
@objc func openDocument(){
    documentPickerVC = UIDocumentPickerViewController(forOpeningContentTypes: [UTType("public.item")!, UTType("public.data")!], asCopy: true )
    documentPickerVC.delegate = self
    documentPickerVC.modalPresentationStyle = .formSheet
    documentPickerVC.directoryURL = documentURL
    self.present(documentPickerVC, animated: true)
}

Solution

  • So, the reason documentURL isn't working is because Apple doesn't support it: specifically, “ This property has no effect in Mac apps built with Mac Catalyst.”