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
相关产品推荐
相关产品推荐

