我正在尝试打开仅允许某些文件类型的选择器。 我正在使用此文档来查找我需要的 UTTYpe: https://developer.apple.com/documentation/uniformtypeidentifiers/uttype/system_declared_uniform_type_identifiers
但我找不到 .pages、.doc、.docx 等 UTTYpe...
我该怎么办?
这是我目前的代码
func presentPickerDocument() {
//Create a picker specifying file type and mode
var supportedTypes: [UTType]
supportedTypes = [UTType.pdf, UTType.url]
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes, asCopy: true)
documentPicker.delegate = self
documentPicker.allowsMultipleSelection = false
present(documentPicker, animated: true, completion: nil)
}
您可以从文件扩展名创建
UTType
,如下所示:
UTType(tag: "pages", tagClass: .filenameExtension, conformingTo: nil)
这会创建一个
UTType?
,因为不能有 UTType
与给定的文件扩展名关联。
您还可以使用:
UTType(filenameExtension: "pages")
但是如果文件扩展名继承自
UTType
,这只会找到 public.data
,因此它不适用于所有文件扩展名。
在 macOS 终端上,您还可以使用
mdls
命令检查文件的统一类型标识符
mdls -name kMDItemContentType yourFile.pages
或其整棵树:
mdls -name kMDItemContentTypeTree yourFile.pages
之后,您可以使用其标识符创建一个
UTType
,如下所示:
UTType("com.apple.iwork.pages.sffpages")
我编写了一个小函数来将字符串数组转换为 UTType 数组以与文件类型一起使用。这仅适用于 macOS 11 及更高版本的项目。
func stringarray2content (_ stringArray: [String]) -> [UTType]
{
var contentArray: [UTType] = []
if (stringArray.count > 0)
{
for i in 1...stringArray.count
{
contentArray.append(UTType(tag: stringArray[i], tagClass: .filenameExtension, conformingTo: nil)!)
}
}
return (contentArray)
}
请确保您已包含 UTType 的库:
import UniformTypeIdentifiers