如何通过UIDocumentMenuViewController限制仅选择PDF和docx文件
嗨,这个问题其实比你想的简单——UIDocumentMenuViewController的allowedUTIs属性本身就支持传入多个UTI字符串,你之前单独允许PDF没问题,本质就是传了单元素的数组,现在只要把DOCX对应的UTI也加进去就行。
首先得明确两种格式对应的正确系统UTI(Uniform Type Identifier):
- PDF对应的UTI是
com.adobe.pdf - DOCX对应的UTI是
org.openxmlformats.wordprocessingml.document
接下来直接把这两个UTI放进数组里,传给UIDocumentMenuViewController的初始化方法就行。给你举个Swift的示例:
// 定义允许的文件类型UTI数组 let allowedFileTypes = ["com.adobe.pdf", "org.openxmlformats.wordprocessingml.document"] // 初始化文档选择菜单,设置为导入模式 let documentMenu = UIDocumentMenuViewController(documentTypes: allowedFileTypes, in: .import) documentMenu.delegate = self present(documentMenu, animated: true)
如果是用Objective-C开发,逻辑完全一致,只是语法不同:
NSArray *allowedFileTypes = @[@"com.adobe.pdf", @"org.openxmlformats.wordprocessingml.document"]; UIDocumentMenuViewController *documentMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:allowedFileTypes inMode:UIDocumentPickerModeImport]; documentMenu.delegate = self; [self presentViewController:documentMenu animated:YES completion:nil];
小提示:如果之后需要支持更多格式,直接往这个数组里添加对应的标准UTI就可以,系统会自动帮你过滤出符合条件的文件。要注意UTI的拼写必须准确,不然会导致过滤失效哦。
内容的提问来源于stack exchange,提问作者Isuru
相关产品推荐
相关产品推荐

