【问题标题】:How to get correct filename from UIDocumentPicker, didPickDocumentsAt urls: [URL]如何从 UIDocumentPicker、didPickDocumentsAt urls 获取正确的文件名:[URL]
【发布时间】:2019-04-04 03:28:09
【问题描述】:

我正在尝试从UIDocumentPickerViewController 获取扩展名的选定文件名,但文件名的文件扩展名末尾有“]”。关于正确方法的任何建议?

这是我的代码:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    let filename = URL(fileURLWithPath: String(describing:urls)).lastPathComponent // print: myfile.pdf]
    self.pickedFile.append(filename)
    // display picked file in a view
    self.dismiss(animated: true, completion: nil)
}

【问题讨论】:

    标签: ios swift uidocumentpickerviewcontroller


    【解决方案1】:

    切勿将String(describing:) 用于调试输出以外的任何内容。您的代码正在生成 URL 实例数组的调试输出。该输出将类似于:

    [file:///some/directory/someFileA.ext,file:///some/directory/otherFile.ext]

    当然,无论选择多少文件,数组输出都会包含。

    然后,您尝试从 URL 实例数组的调试输出创建文件 URL,然后获取其中的最后一个路径组件。这就是为什么你得到尾随的]

    只需访问您想要的数组中的元素。不要创建新的URL

    if let filename = urls.first?.lastPathComponent {
        self.pickedFile.append(filename)
    }
    

    更好的是,将它们全部添加:

    for url in urls {
        self.pickedFile.append(url.lastPathComponent)
    }
    

    【讨论】:

      【解决方案2】:

      urls 是 URL 数组,不是 URL,不是字符串

      试试:

       func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
          if let filename =  urls.first?.lastPathComponent {
              self.pickedFile.append(filename)
              // display picked file in a view
              self.dismiss(animated: true, completion: nil)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-06
        • 1970-01-01
        • 2010-10-10
        • 1970-01-01
        • 2019-02-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多