我需要打开一个 sqlite 文件并从该文件中读取数据以显示在表格中。 到目前为止,我有一个触发 NSOpenPanel() 的按钮,并获取路径。之后,我尝试打开该文件,但出现编码问题。
在 AppDelegate.swift 中我的代码下方
@IBAction func importFromKobo(sender: AnyObject) {
var openPanel = NSOpenPanel()
let fileDB = "kobodbtest.sqlite"
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = true
openPanel.canCreateDirectories = true
openPanel.canChooseFiles = false
openPanel.beginWithCompletionHandler { (result) -> Void in
if result == NSFileHandlingPanelOKButton {
//Do what you will
//If there's only one URL, surely 'openPanel.URL'
var deviceURL = openPanel.URL!
println("Path: \(deviceURL)")
println(self.resultDev.stringValue)
self.resultDev.stringValue += "\nPath: \(deviceURL)"
self.resultInput.stringValue += "\nPath: \(deviceURL)"
var fullFilePathURL = deviceURL.URLByAppendingPathComponent(fileDB)
self.resultInput.stringValue += "\nFull path file: \(fullFilePathURL)"
var fileOpenError:NSError?
if NSFileManager.defaultManager().fileExistsAtPath(deviceURL.path!) {
println("file OK")
if let fileContent = String(contentsOfURL: fullFilePathURL, encoding: NSUTF8StringEncoding, error: &fileOpenError) {
println(fileContent) // prints ReadMe.txt contents if successful
} else {
if let fileOpenError = fileOpenError {
println(fileOpenError) // Error Domain=NSCocoaErrorDomain Code=XXX "The file “ReadMe.txt” couldn’t be opened because...."
}
}
} else {
println("file not found")
}
}
if result == NSFileHandlingPanelCancelButton {
self.resultDev.stringValue = "Cancel"
}
}
}`
控制台报错:
Path: file:///Users/alvaroruiz/Documents/xcode/
Result
file OK
Error Domain=NSCocoaErrorDomain Code=261 "The file “kobodbtest.sqlite” couldn’t be opened using text encoding Unicode (UTF-8)." UserInfo=0x60000026cb00 {NSFilePath=/Users/alvaroruiz/Documents/xcode/kobodbtest.sqlite, NSStringEncoding=4}
我检查了 sqlite> PRAGMA 编码;
格式是 UTF-8。
检查了其他编码,如 NSISOLatin1StringEncoding 并得到了文本,但有很多符号。
你能告诉我如何执行查询命令吗?并显示在表格中?
谢谢。 阿尔瓦罗
最佳答案
您正在检查您刚刚选择的路径是否存在,这是不必要的。我猜您想改为检查最终文件:
if NSFileManager.defaultManager().fileExistsAtPath(fullFilePathURL.path!)
接下来,Leonardo 的评论是正确的,您可以使用NSUTF16StringEncoding
读取文件:
if let fileContent = String(contentsOfURL: fullFilePathURL, encoding: NSUTF16StringEncoding, error: &fileOpenError) {
但是 sqlite 数据库不是文本文件,仅以文本形式阅读纯内容不会让您走得太远。 :) 所以你应该使用专用工具来处理它,比如 SQLite.swift .这将允许您运行查询并在表格中显示结果。
关于macos - 打开 sqlite 文件 swift osx 应用程序并读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29632164/