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

iOS 16下如何将UTI字符串列表转换为UTType列表?

iOS 16 下 UTI 字符串转 UTType 列表的实现方案

需求背景

应用保留了一份统一类型标识符(UTI)字符串列表:

public static let supportedUTIs = ["public.text", "public.image", "com.adobe.pdf", "public.comma-separated-values-text", "com.microsoft.word.doc", "org.openxmlformats.wordprocessingml.document", "com.microsoft.excel.xls", "org.openxmlformats.spreadsheetml.sheet", "com.microsoft.powerpoint.ppt", "org.openxmlformats.presentationml.presentation", "com.apple.iwork.pages.pages", "com.apple.iWork.Numbers.numbers", "com.apple.keynote.key"]

升级iOS 16最低部署目标后,UIDocumentPickerViewController(documentTypes:in:)被弃用,替代APIUIDocumentPickerViewController(forOpeningContentTypes:)要求传入[UTType]类型参数,需将现有UTI字符串列表转换为该类型,同时保留原字符串列表供其他模块使用。

解决方案

使用iOS 14+引入的UTType(string:)初始化方法,遍历原字符串列表并过滤无效值,即可得到符合要求的[UTType]数组:

转换代码实现

// 保留原UTI字符串列表不变
public static let supportedUTIs = ["public.text", "public.image", "com.adobe.pdf", "public.comma-separated-values-text", "com.microsoft.word.doc", "org.openxmlformats.wordprocessingml.document", "com.microsoft.excel.xls", "org.openxmlformats.spreadsheetml.sheet", "com.microsoft.powerpoint.ppt", "org.openxmlformats.presentationml.presentation", "com.apple.iwork.pages.pages", "com.apple.iWork.Numbers.numbers", "com.apple.keynote.key"]

// 转换为UTType列表,自动过滤无效UTI字符串
public static var supportedContentTypes: [UTType] {
    supportedUTIs.compactMap { UTType(string: $0) }
}

关键说明

  • UTType(string:)是苹果推荐替代旧kUTType常量的API,支持直接通过UTI字符串实例化UTType对象,完全兼容iOS 16。
  • 使用compactMap而非map,可自动过滤掉无法识别的UTI字符串(如拼写错误的无效值),避免数组中混入nil,确保传入文档选择器的参数全部有效。

文档选择器使用示例

// 创建iOS 16+兼容的文档选择器
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: YourClassName.supportedContentTypes)
documentPicker.delegate = self
present(documentPicker, animated: true)

兼容iOS 15及以下版本(可选)

如果需要兼顾旧系统,可通过条件编译区分API调用:

let documentPicker: UIDocumentPickerViewController
if #available(iOS 16, *) {
    documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: YourClassName.supportedContentTypes)
} else {
    documentPicker = UIDocumentPickerViewController(documentTypes: YourClassName.supportedUTIs, in: .import)
}
documentPicker.delegate = self
present(documentPicker, animated: true)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:15:21