迅捷的文档选择器,无法访问文件



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

下面是它调用文档选取器的函数。它由按钮激活。

@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]。

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

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

就我而言,行为不会改变,我可以选择一个文件而不会丢失预期的行为。

文件url 不同,因为它就像它说如果你选择 .import 它导入到应用程序临时文件。要获取原始文件 url,您应该选择 .open

最新更新