Swift文档选择器,无法访问文件

Swift文档选择器,无法访问文件,swift,xcode,Swift,Xcode,我正在写一个项目,其中包括选择一个文件,并获得文件的内容。但是,我认为它没有到达文件的正确url 下面是它调用文档选择器的函数。它由一个按钮启动 @IBAction func selectFile(_ sender: Any) { let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypePlainText as String], in: .import) document

我正在写一个项目,其中包括选择一个文件,并获得文件的内容。但是,我认为它没有到达文件的正确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}}}
无法关联拾取的URL的缩略图
file:///Users//Library/Developer/CoreSimulator/Devices/480A2D02-810F-435E-BF44-4B2F6FC614A9/data/Containers/Data/Application/BAA825D0-C4D8-4B33-AFB3-3737ADCA0B29/Documents/test2.txt 使用收件箱副本
file:///Users//Library/Developer/CoreSimulator/Devices/480A2D02-810F-435E-BF44-4B2F6FC614A9/data/Containers/Data/Application/BAA825D0-C4D8-4B33-AFB3-3737ADCA0B29/tmp/-Inbox/test2.txt: 
错误域=QLThumbnailErrorDomain代码=102“(空)”
UserInfo={NSUnderlyingError=0x60000338060
{Error Domain=GSLibraryErrorDomain Code=3“找不到生成”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]

也许它能解决你的问题。请让我知道反馈。
我知道这是一个老问题,但如果它对任何人都有帮助,我通过更改
UIDocumentPickerViewController
的实例类型,输入.open而不是.import,解决了控制台问题


在我的情况下,行为不会改变,我可以选择一个文件而不会丢失预期的行为。

实际上它是针对iOS应用程序的,对吗?