Swift Document Picker,无法访问文件

标签 swift xcode

我正在编写一个项目,其中涉及选择一个文件并获取文件的内容。但是,我认为它没有到达文件的正确 url。

这是调用文档选择器的函数。它由一个按钮激活。

@IBAction func selectFile(_ sender: Any) {
        let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypePlainText as String], in: .import)
        documentPicker.delegate = self
        documentPicker.allowsMultipleSelection = false
        present(documentPicker, animated: true, completion: nil)
}

这是对 UIDocumentPickerViewController 的扩展
extension ViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        print(urls)
        do {
            let fileContent = try String(contentsOf: urls[0], encoding: .utf8)
            print(fileContent)
        } catch {
            return
        }
    }
}

在控制台输出中,fileContent没有被打印出来,相反,这是它打印出来的。
Failed to associate thumbnails for picked URL
file:///Users/<user>/Library/Developer/CoreSimulator/Devices/480A2D02-810F-435E-BF44-4B2F6FC614A9/data/Containers/Data/Application/BAA825D0-C4D8-4B33-AFB3-3737ADCA0B29/Documents/test2.txt with the Inbox copy 
file:///Users/<user>/Library/Developer/CoreSimulator/Devices/480A2D02-810F-435E-BF44-4B2F6FC614A9/data/Containers/Data/Application/BAA825D0-C4D8-4B33-AFB3-3737ADCA0B29/tmp/<project>-Inbox/test2.txt: 
Error Domain=QLThumbnailErrorDomain Code=102 "(null)" 
UserInfo={NSUnderlyingError=0x600003348060 
{Error Domain=GSLibraryErrorDomain Code=3 "Generation not found" UserInfo={NSDescription=Generation not found}}}

网上关于这个的资源不多,有人可以帮忙看看我在这里做错了什么吗?

最佳答案

实际上我对 UIDocumentPickerViewController 初始化程序做了一个小改动。添加下面的更新代码。

@IBAction func selectFile(_ sender: Any) {
    let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.text"], in: .import)
    documentPicker.delegate = self
    documentPicker.allowsMultipleSelection = false
    present(documentPicker, animated: true, completion: nil) }

其余代码相同,仅替换了 ["public.text"] 而不是 [kUTTypePlainText as String]。

也许它可以解决您的问题。请让我知道反馈。
信用转至 adrian检查此链接 using-uidocumentpickerviewcontroller-to-import-text-in-swift

关于Swift Document Picker,无法访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59913721/

相关文章:

ios - 以编程方式查看 Controller ?

ios - UITableViewCell socket

swift - iOS 模拟器需要 1 个多小时才能运行一个应用程序

xcode - 错误 "Thread 1: breakpoint 2.1"

ios - UITableView 中所有单元格的模糊效果背景

ios - Xcode build设置 - 在生产构建中从 plist 中删除代码

ios - 如何让一个按钮根据发送的变量连接到多个 View Controller ,并发送一个新变量

ios - 在 ButtonRow 中显示值

Swift 字典需要很长时间才能编译

ios - 具有可选函数实现的 Swift @objc 协议(protocol)会导致构建错误