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

UIDocumentPickerViewController的init(documentTypes:in:)iOS14废弃如何做版本兼容?

UIDocumentPickerViewController 跨版本适配方案

核心适配思路

通过系统版本分支判断,分别调用对应版本的初始化方法:

  • iOS 14.0 及以上版本使用官方推荐的新API init(forOpeningContentTypes:asCopy:)
  • iOS 13.0 及更早版本沿用旧的废弃API init(documentTypes:in:),苹果允许低版本系统调用已废弃API,不会触发审核问题

Swift 实现代码

import UIKit
import UniformTypeIdentifiers // iOS 14+ 依赖框架
import MobileCoreServices // 旧版本依赖框架

func showDocumentPicker() {
    let picker: UIDocumentPickerViewController
    // 按需调整你需要支持的文件类型,此处示例为支持所有类型文件
    if #available(iOS 14.0, *) {
        let supportedTypes: [UTType] = [.item]
        // asCopy: true 对应旧版 .import 模式,asCopy: false 对应旧版 .open 模式
        picker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes, asCopy: true)
    } else {
        let supportedTypes: [String] = [kUTTypeItem as String]
        picker = UIDocumentPickerViewController(documentTypes: supportedTypes, in: .import)
    }
    // 通用配置
    picker.delegate = self
    picker.allowsMultipleSelection = false
    present(picker, animated: true)
}

Objective-C 实现代码

#import <UIKit/UIKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#endif

- (void)showDocumentPicker {
    UIDocumentPickerViewController *picker;
    if (@available(iOS 14.0, *)) {
        NSArray *supportedTypes = @[UTTypeItem];
        picker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:supportedTypes asCopy:YES];
    } else {
        NSArray *supportedTypes = @[(NSString *)kUTTypeItem];
        picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:supportedTypes inMode:UIDocumentPickerModeImport];
    }
    picker.delegate = self;
    picker.allowsMultipleSelection = NO;
    [self presentViewController:picker animated:YES completion:nil];
}

注意事项

  • 若需要限定文件类型,只需替换对应类型标识即可:例如仅选择PDF文件,旧版传 kUTTypePDF as String,新版传 UTType.pdf
  • 新API的asCopy参数需和旧版in参数的枚举值保持业务逻辑一致,避免文件访问权限问题
  • 两个版本的代理回调方法完全通用,不需要额外做适配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:15:04