Check condition for a zip file in UIDocumentPickerViewController
Asked Answered
R

2

0

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!

Rorke answered 21/8, 2020 at 10:20 Comment(0)
R
0

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"
    }
}
Rorke answered 24/8, 2020 at 10:16 Comment(0)
R
1

Intialize the DocumentPicker with the list of supported types.

    let zip = ["com.pkware.zip-archive"]
    let importMenu = UIDocumentPickerViewController(documentTypes: zip, in: .import)

Here's a list of supported UTIs

Reinertson answered 21/8, 2020 at 13:31 Comment(1)
hi and thank you for the answer. Basically, this is the same as what I am using, you just make initialize the type separately: let importMenu = UIDocumentPickerViewController(documentTypes: [String(kUTTypeArchive)], in: .open ) The problem is that .docx is considered to be an archive as well. https://mcmap.net/q/271212/-what-is-the-structure-of-a-docx-and-doc-file en.wikipedia.org/wiki/Office_Open_XMLRorke
R
0

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"
    }
}
Rorke answered 24/8, 2020 at 10:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.