使用UIDropInteraction获取拖拽多文件URL时丢失文件如何解决?
问题根因
你遇到的两个问题均符合UIDropInteraction的系统设计逻辑:
- 大量文件拖拽丢失:
loadInPlaceFileRepresentation是异步执行的接口,所有文件的加载回调还没全部返回,sessionDidEnd就已经被系统触发,此时你读取的droppedURLs只包含已完成加载的部分文件,自然出现数量缺失。 sessionDidEnd中调用加载接口报错:UIDropSession生命周期结束时,系统会立即回收会话持有的文件安全访问令牌、itemProvider相关资源,此时再发起加载请求会直接被系统拒绝,返回你遇到的-1000错误。
解决方案
不要依赖sessionDidEnd触发文件打开逻辑,在performDrop中使用DispatchGroup追踪所有异步加载任务的完成状态,等全部文件加载完成后再统一处理即可。
修正后的核心代码如下:
// 可选:如果你的droppedURLs仅在拖拽场景使用,可以直接改为performDrop内的局部变量,无需全局存储 var droppedURLs: [URL] = [] func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { return session.hasItemsConforming(toTypeIdentifiers: ["public.item"]) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { return UIDropProposal(operation: .copy) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { droppedURLs.removeAll() let loadGroup = DispatchGroup() // 统一使用主队列操作数组和UI逻辑,保证线程安全 let targetQueue = DispatchQueue.main for item in session.items { loadGroup.enter() item.itemProvider.loadInPlaceFileRepresentation(forTypeIdentifier: "public.item") { [weak self] url, _, error in // 无论加载成功失败,都要标记任务完成,避免group永远卡住 defer { loadGroup.leave() } guard let self = self, let loadUrl = url, error == nil else { // 单个文件加载失败可在此处添加日志统计,不影响其他文件处理 return } targetQueue.async { self.droppedURLs.append(loadUrl) } } } // 所有加载任务完成后触发后续逻辑 loadGroup.notify(queue: targetQueue) { [weak self] in guard let self = self, !self.droppedURLs.isEmpty else { return } self.openURLs(self.droppedURLs) // 处理完成后清空临时存储,避免重复处理 self.droppedURLs.removeAll() } } func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnd session: UIDropSession) { // 此处仅需做状态重置即可,不要发起任何itemProvider加载请求 }
额外注意点
- 不要使用强制解包
self!和url!,页面销毁、单个文件加载失败的场景下强制解包会直接引发崩溃,使用可选绑定更安全。 - 对
droppedURLs的读写操作必须放在同一个串行队列(示例中用了主队列)执行,避免多线程同时读写数组出现数据错乱、野指针问题。 - 如果需要支持上千个超大数量文件拖拽,可以在开始加载时添加loading提示,避免用户误以为应用无响应。
内容的提问来源于stack exchange,提问作者shuna
相关产品推荐
相关产品推荐

