在UIDocumentPickerViewController中检查zip文件的条件

问题描述

这是我的代码,用于调用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"
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...