You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS14下UIDocumentPickerViewController的documentPickerMode废弃后如何区分导入导出模式

适配iOS14+ UIDocumentPickerViewController模式判断解决方案

核心原因

iOS14及以上系统废弃了UIDocumentPickerViewController的documentPickerMode属性,官方改为通过不同的初始化方法明确区分导入/导出场景,因此需要自行存储模式信息用于回调判断。


方案1:使用关联对象自定义存储模式(最通用)

给UIDocumentPickerViewController加扩展,新增自定义的模式存储属性:

import UIKit
import ObjectiveC.runtime

private var kDocumentPickerCustomModeKey: Void?

extension UIDocumentPickerViewController {
    enum CustomPickerMode {
        case `import`
        case export
        // 可根据需要补充open、move等其他模式
    }
    
    var customPickerMode: CustomPickerMode? {
        get {
            objc_getAssociatedObject(self, &kDocumentPickerCustomModeKey) as? CustomPickerMode
        }
        set {
            objc_setAssociatedObject(self, &kDocumentPickerCustomModeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

初始化时赋值模式

  • 导入模式初始化示例:
// 导入场景,UTType根据自身业务调整
let importPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: true)
importPicker.customPickerMode = .import
importPicker.delegate = self
present(importPicker, animated: true)
  • 导出模式初始化示例:
// 导出场景,替换为你需要导出的文件URL
let exportPicker = UIDocumentPickerViewController(forExporting: [targetFileURL], asCopy: true)
exportPicker.customPickerMode = .export
exportPicker.delegate = self
present(exportPicker, animated: true)

回调时判断模式

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    // 兼容新旧系统版本
    if #available(iOS 14, *) {
        guard let mode = controller.customPickerMode else { return }
        switch mode {
        case .import:
            // 原有导入模式逻辑
        case .export:
            // 原有导出模式逻辑
        }
    } else {
        // iOS13及以下仍使用系统原有属性判断
        switch controller.documentPickerMode {
        case .import:
            // 导入逻辑
        case .exportToService:
            // 导出逻辑
        default:
            break
        }
    }
}

方案2:多代理区分(适合业务场景分离的项目)

如果你的导入、导出选择器分别在不同的业务类中触发,也可以给两种场景的picker设置不同的代理对象,分别实现各自的回调逻辑,无需额外做模式判断。

内容的提问来源于stack exchange,提问作者Francesco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 17:54:03