【问题标题】:Get file from Url or path?从 URL 或路径获取文件?
【发布时间】:2018-01-29 05:38:53
【问题描述】:

我已集成 UIDocumentPickerDelegateUIDocumentMenuDelegate 我在从 URL 或 DocumentPicker 获取文件时遇到问题。如何在 iOS swift 中解决这个问题?

【问题讨论】:

  • 你遇到什么问题,写在这里。
  • 我从 UIDocumentPickerDelegate 获取文件 url 但我需要获取文件。
  • Edit 您的问题包括您的相关代码(作为文本)并清楚地显示您需要帮助的地方。
  • 什么样的文件?到目前为止,您的解决方案是什么?
  • 我需要获取 .pdf、.txt、.apk 等文件。@Roy

标签: ios swift uidocumentpickerviewcontroller


【解决方案1】:

您可以轻松获取文件,

如果需要获取图片

    @IBAction func btn_Handler_iCloud(_ sender: Any) {
        let doc = UIDocumentMenuViewController(documentTypes: [String(kUTTypeImage)], in: .import)
        doc.delegate = self
        doc.modalPresentationStyle = .formSheet
        self.present(doc, animated: true, completion: nil)
    }

    func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
        documentPicker.delegate = self
        present(documentPicker, animated: true, completion: nil)
    }

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        let data = try! Data(contentsOf: urls[0])
        imageview_Buaty.image = UIImage.init(data: data)
    }

    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        dismiss(animated: true, completion: nil)
    }

【讨论】:

    【解决方案2】:

    从 UIDocumentPickerViewController 获取文档 URL 或数据:

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { 
        // Available from iOS 8.0 to iOS 11.0
        self.handleFileSelection(inUrl: url)// Here url is document's URL
    }
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        // Available from iOS 11.0
        self.handleFileSelection(inUrl: urls.first!)  // Here urls is array of URLs
    }
    
    private func handleFileSelection(inUrl:URL) -> Void {
        do { 
         // inUrl is the document's URL
            let data = try Data(contentsOf: inUrl) // Getting file data here
        } catch {
            dLog(message: "document loading error")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2011-11-06
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2021-10-15
      • 2011-11-16
      相关资源
      最近更新 更多