如何获取UIDocumentMenu/UIDocumentPicker所选文件的来源?
检测UIDocumentPicker所选文件的来源
我之前也碰到过这个需求,确实苹果没有提供直接返回文件来源的官方API,但试下来有几个可行的变通办法,能帮你识别文件是来自Files、Google Drive还是DropBox这类服务:
方法1:通过URL的资源属性获取容器名称
当文件来自云存储服务时,你可以从文件URL的资源属性里拿到对应的容器名称,这个名称通常就是服务的官方名称:
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { do { let resourceKeys: Set<URLResourceKey> = [.ubiquitousContainerDisplayNameKey] let resourceValues = try url.resourceValues(forKeys: resourceKeys) if let containerName = resourceValues.ubiquitousContainerDisplayName { // 这里的containerName就是来源服务名,比如"iCloud Drive"、"Google Drive" print("文件来源:\(containerName)") } else { // 说明是本地文件或者无法识别的来源 print("文件来自本地存储或未知来源") } } catch { print("获取资源属性失败:\(error.localizedDescription)") } }
注意:这个方法只对云存储类服务有效,本地文件(比如Files应用里的本地文件夹)会返回nil。
方法2:从DocumentPicker的导航栏标题判断
在用户选择来源后的documentMenu(_:didPickDocumentPicker:)代理方法里,刚选中的UIDocumentPickerViewController的导航栏标题,通常就是对应的服务名称:
func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { // 先获取来源名称再present选择器 if let navVC = documentPicker.viewControllers.first as? UINavigationController, let sourceName = navVC.topViewController?.title { print("用户选择的文件来源:\(sourceName)") } present(documentPicker, animated: true) }
这个方法的局限性是依赖第三方开发者遵循规范设置导航栏标题,但像Google Drive、DropBox这类主流服务都会这么做,实用性很强。
方法3:通过URL路径特征辅助判断
部分云服务的文件URL路径里会包含特定标识,比如Dropbox的路径里会有"Dropbox"字符串,你可以通过检查路径来辅助判断:
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { let filePath = url.path switch filePath { case let path where path.contains("iCloud"): print("来源:iCloud Drive") case let path where path.contains("Google Drive"): print("来源:Google Drive") case let path where path.contains("Dropbox"): print("来源:Dropbox") default: print("未知来源") } }
不过这个方法不够健壮,因为路径格式可能随服务版本更新变化,建议和前两种方法结合使用。
你可以根据自己的需求组合这些方法,基本能覆盖大部分常见的文件来源场景。
内容的提问来源于stack exchange,提问作者user9749232
相关产品推荐
相关产品推荐

