我正在编写一个项目,其中涉及选择一个文件并获取文件的内容。但是,我认为它没有到达文件的正确 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/