如何接收Files App发送给iOS应用的多个文件?
解决iOS应用接收Files App多文件分享的问题
你碰到的这个问题核心在于:你目前只实现了处理单文件分享的回调方法,系统在处理多文件分享时,会优先调用专门的多URL处理接口,如果没实现它,就只会触发单URL的方法,而且只传入第一个文件的URL。另外你提到的文件夹权限问题,是因为分享的文件都是通过「安全作用域书签」授权的单个文件权限,而非整个文件夹的访问权限,所以直接遍历文件夹肯定会被拒绝。
下面是具体的解决步骤:
1. 实现多文件分享的回调方法
在AppDelegate中添加(或补充原有单文件方法)application(_:openURLs:options:)方法,这个方法会接收所有被分享的文件URL数组:
func application(_ application: UIApplication, openURLs urls: [URL], options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // 获取你的目标视图控制器 guard let pickFilesVC = window?.rootViewController as? FirstViewController else { return false } // 遍历所有分享的文件URL for url in urls { // 开启安全作用域访问(必须步骤,沙盒外文件需要临时授权) guard url.startAccessingSecurityScopedResource() else { print("无法获取文件权限: \(url.lastPathComponent)") continue } // 创建你的FileItem并赋值 let sharedItem = FileItem() sharedItem.path = url sharedItem.name = url.lastPathComponent sharedItem.image = self.loadUIImage(fileURL: url) // 添加到选中文件列表 pickFilesVC.selectedFiles.append(sharedItem) // 必须结束安全作用域访问,释放权限 url.stopAccessingSecurityScopedResource() } // 刷新表格 pickFilesVC.filesTableView.reloadData() return true }
2. 保留单文件处理(可选)
如果你还需要支持单个文件的分享场景,可以保留原来的application(_:open:options:)方法,这样单文件和多文件分享都能被正确处理:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { guard let pickFilesVC = window?.rootViewController as? FirstViewController else { return false } guard url.startAccessingSecurityScopedResource() else { print("无法访问文件: \(url.lastPathComponent)") return false } let sharedItem = FileItem() sharedItem.path = url sharedItem.name = url.lastPathComponent sharedItem.image = self.loadUIImage(fileURL: url) pickFilesVC.selectedFiles.append(sharedItem) pickFilesVC.filesTableView.reloadData() url.stopAccessingSecurityScopedResource() return true }
关键注意事项
- 安全作用域访问必须配对使用:
startAccessingSecurityScopedResource()和stopAccessingSecurityScopedResource()必须成对调用,否则会导致权限泄漏,后续访问文件可能失败。 - 不要尝试遍历文件夹:系统不会给你分享文件夹的权限,每个文件的URL都是独立授权的,只能通过
urls数组逐个处理文件。 - 确认Info.plist配置:确保你的
CFBundleDocumentTypes配置正确,包含了你支持的文件扩展名对应的UTI,并且LSHandlerRank设置为Alternate或Default,这样Files App才会把你的应用列在分享选项中。
这样修改后,你的应用就能一次性接收所有从Files App分享过来的同类型文件了。
内容的提问来源于stack exchange,提问作者Asiimwe




