Mac Catalyst 的备用 UIActivityViewController 保存对话框或 UIDocumentPickerViewController 抛出错误代码 260 的解决方案

Alternative UIActivityViewController save dialog for Mac Catalyst or solution for UIDocumentPickerViewController throwing error code 260

我正在为 Mac Catalyst 应用程序寻找除 UIActivityViewController 之外的替代导出菜单。虽然这有效,但用户无法选择他们想要保存文件的位置(该文件是列表中所有项目的 JSON 文件),我希望用户能够选择他们想要的目录将 JSON 保存到。我尝试了以下代码,但是当您尝试保存文件时它给出了错误 "Error Domain=NSCocoaErrorDomain Code=260 'The file 'name.json' couldn’t be opened because there is no such file'"。

代码:

let fileManager = FileManager.default

do {
    let fileURL2 = fileManager.temporaryDirectory.appendingPathComponent("\(detailedList.lname!).json")

    // Write the data out into the file
    try jsonData.write(to: fileURL2)

    // Present the save controller. We've set it to `exportToService` in order
    // to export the data -- OLD COMMENT
    let controller = UIDocumentPickerViewController(url: fileURL2, in: UIDocumentPickerMode.exportToService)
    present(controller, animated: true) {
        // Once we're done, delete the temporary file
        try? fileManager.removeItem(at: fileURL2)
    }
} catch {
    print("error creating file")
}

我已经尝试通过谷歌搜索其他方式或方法来实现它,但我找不到任何适用于 Mac Catalyst 的东西。我知道你可以做到这一点,因为我已经看到其他应用程序和示例可以做到这一点,但对我来说没有任何效果。那么执行此操作的可能替代方法或此代码的解决方案是什么?

问题是您在用户有机会选择他们想要保存文件的位置之前就删除了您想要保存的文件。

您调用 try? fileManager.removeItem(at: fileURL2) 的完成处理程序会在显示文档选择器时立即调用。

正确的解决方案是在 UIDocumentPickerDelegate 方法中删除文件,而不是在显示选择器时。