open sqlite file swift osx app and read data -
i need open sqlite file , read data file show in table. far have button trigger nsopenpanel(), , path. after tried open file have encoding problem.
below code in 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 //if there's 1 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 opened because...." } } } else { println("file not found") } } if result == nsfilehandlingpanelcancelbutton { self.resultdev.stringvalue = "cancel" } } }`
and error in console:
path: file:///users/alvaroruiz/documents/xcode/ result file ok error domain=nscocoaerrordomain code=261 "the file “kobodbtest.sqlite” couldn’t opened using text encoding unicode (utf-8)." userinfo=0x60000026cb00 {nsfilepath=/users/alvaroruiz/documents/xcode/kobodbtest.sqlite, nsstringencoding=4}
i have checked usign sqlite> pragma encoding;
format utf-8.
checked other encoding nsisolatin1stringencoding , text lot of symbols.
could point me how query command? , display in table?
thanks. alvaro
you're checking if path selected exists, it's unnecessary. guess wanted check final file instead:
if nsfilemanager.defaultmanager().fileexistsatpath(fullfilepathurl.path!)
next, leonardo right in comment, can read file using nsutf16stringencoding
:
if let filecontent = string(contentsofurl: fullfilepathurl, encoding: nsutf16stringencoding, error: &fileopenerror) {
but sqlite database not text file, , reading plain content text won't far. :) should rather use dedicated tool deal it, sqlite.swift. allow run queries , display results in table.
Comments
Post a Comment