Search code examples
iosswiftzipuidocumentpickerviewcontroller

Check condition for a zip file in UIDocumentPickerViewController


This is my code for calling UIDocumentPickerViewController to choose the files for my firmware update which have to be .zip only. When I press on "Select" button, the Document Picker View shows up:

@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)
  }
}

Right now it's possible to open the files in .docx format, but I need to only let the user pick one format - a zip file.

I cannot present what I have done so far because I am not able to find a solution. Is there a way to make a check for a zip file or just forbid selecting other formats? Thank you!


Solution

  • In my view's extension I use the UIDocumentPickerDelegate and in the function I check if my file's last component is 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"
        }
    }