首页 > 解决方案 > 保存文件时选择目的地

问题描述

是否可以让用户为他想要下载的文件选择一个目的地,比如在选择要上传的文件时可以使用的 DocumentPicker?
我想要这样的东西: 图像1

标签: iosswiftnsfilemanagerfile-manageruidocumentpickerviewcontroller

解决方案


是的,对于 iOS 13 及更高版本,您可以要求用户通过UIDocumentPickerViewController. 您将获得用户选择的目录的安全范围 url。

此处的详细信息:https ://developer.apple.com/documentation/uikit/view_controllers/providing_access_to_directories

我已经从下面那个页面粘贴了示例代码,但是您需要仔细阅读文档,因为安全范围的 URL 需要小心处理:)

如果您需要 iOS 12 或更早版本,用户只能选择文件,所以我不清楚执行此操作的干净方式(但我们在 iOS 14 上,iOS 15 即将推出,所以希望您不必支持回到iOS 13)。

这是上面链接中的示例代码,显示了这是如何完成的:

// Create a document picker for directories.
let documentPicker =
    UIDocumentPickerViewController(forOpeningContentTypes: [.folder])
documentPicker.delegate = self

// Set the initial directory.
documentPicker.directoryURL = startingDirectory

// Present the document picker.
present(documentPicker, animated: true, completion: nil)

推荐阅读