问题描述
这是我的代码,用于调用UIDocumentPickerViewController来选择我的固件更新文件,这些文件必须仅为.zip
。当我按“选择”按钮时,将显示“文档选择器视图”:
@IBAction func selectButtonAction(_ sender: UIButton) {
if sender.title(for: .normal) == "Select"{
if let controller = (UIApplication.shared.delegate as? AppDelegate)?.currentViewController {
let importMenu = UIDocumentPickerViewController(documentTypes: [String(kUTTypeArchive)],in: .open )
importMenu.delegate = self
importMenu.modalPresentationStyle = .formSheet
controller.present(importMenu,animated: true,completion: nil)
}
} else {
changeDFUItemsDesign(isFileURLNil: true)
}
}
现在可以打开.docx
格式的文件,但是我只需要让用户选择一种格式-zip文件即可。
由于无法找到解决方案,所以我无法介绍我到目前为止所做的事情。有没有办法检查zip文件或只是禁止选择其他格式?谢谢!
解决方法
使用支持的类型列表初始化DocumentPicker。
let zip = ["com.pkware.zip-archive"]
let importMenu = UIDocumentPickerViewController(documentTypes: zip,in: .import)
Here是受支持的UTI的列表
,在我的视图扩展名中,我使用UIDocumentPickerDelegate
,并在函数中检查文件的最后一个组件是否为zip:
func documentPicker(_ controller: UIDocumentPickerViewController,didPickDocumentsAt urls: [URL]) {
if let fileURL = urls.first,fileURL.pathExtension == "zip" {
self._fileURL = fileURL
self.fileNameLabel.text = _fileURL?.lastPathComponent
} else {
_fileURL = nil
fileNameLabel.text = "Select file"
}
}