Kiểm tra điều kiện cho tệp zip trong UIDocumentPickerViewController
Đây là mã của tôi để gọi UIDocumentPickerViewController để chọn các tệp cho bản cập nhật chương trình cơ sở của tôi .zip. Khi tôi nhấn vào nút "Chọn", Chế độ xem Bộ chọn Tài liệu sẽ hiển thị:
@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)
}
}
Hiện tại, có thể mở tệp ở .docxđịnh dạng, nhưng tôi chỉ cần cho phép người dùng chọn một định dạng - tệp zip.
Tôi không thể trình bày những gì tôi đã làm cho đến nay vì tôi không thể tìm ra giải pháp. Có cách nào để kiểm tra tệp zip hay chỉ cấm chọn các định dạng khác? Cảm ơn bạn!
Trả lời
Liên kết với DocumentPicker với danh sách các loại được hỗ trợ.
let zip = ["com.pkware.zip-archive"]
let importMenu = UIDocumentPickerViewController(documentTypes: zip, in: .import)
Đây là danh sách các UTI được hỗ trợ
Trong phần mở rộng của chế độ xem của tôi, tôi sử dụng UIDocumentPickerDelegatevà trong hàm, tôi kiểm tra xem thành phần cuối cùng của tệp của tôi có phải là zip hay không:
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"
}
}