我试图将我的sqlite数据库文件上传到应用程序中。我一直在学习iOS文件系统,而且我不完全确定它是如何工作的并且迷路了。这就是我想要实现的目标,但不确定如何:
提前谢谢!!!
我的代码看起来像这样:
func prepareDatabaseFile() -> String {
let fileName: String = "foo.sqlite"
let filemanager:FileManager = FileManager.default
let directory = filemanager.urls(for: .documentDirectory, in: .userDomainMask).first!
let newUrl = directory.appendingPathComponent(fileName)
let bundleUrl = Bundle.main.resourceURL?.appendingPathComponent(fileName)
// check bundle
if filemanager.fileExists(atPath: (bundleUrl?.path)!) {
print("bundle file exists!")
return (bundleUrl?.path)! //probably I need to copy from bundle to new app and return new url
// here check if file already exists on simulator, but not in bundle
} else if filemanager.fileExists(atPath: (newUrl.path)) {
print("prebuild file exists!")
return newUrl.path //no copy is needed
// finally, if nothing I need to copy local file
} else {
//todo copy local file from the path my-xcode-project-path/data/foo.sqlite
print("todo")
}
return fileName
}
答案 0 :(得分:3)
在@ Rob的帮助下,我开始遵循满足我要求的解决方案。以前有必要将sqlite文件添加到xcode项目中,并使用适当的目标。
func prepareDatabaseFile() -> String {
let fileName: String = "foo.sqlite"
let fileManager:FileManager = FileManager.default
let directory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let documentUrl= directory.appendingPathComponent(fileName)
let bundleUrl = Bundle.main.resourceURL?.appendingPathComponent(fileName)
// here check if file already exists on simulator
if fileManager.fileExists(atPath: (documentUrl.path)) {
print("document file exists!")
return documentUrl.path
else if fileManager.fileExists(atPath: (bundleUrl?.path)!) {
print("document file does not exist, copy from bundle!")
fileManager.copyItem(at:bundleUrl, to:documentUrl)
}
return documentUrl.path
}
答案 1 :(得分:0)
self.copyfile(filename: "mydata.sqlite" )
return true
}
func copyfile(filename : String)
{
let dbpath : String = getpath(filename: filename as String)
let filemanager = FileManager.default
if filemanager.fileExists(atPath: dbpath)
{
let documentsURl = Bundle.main.resourceURL
let frompath = documentsURl?.appendingPathComponent(filename)
print(frompath)
}
}
func getpath(filename: String) -> String
{
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
print(documentsURL)
let fileURL = documentsURL.appendingPathComponent(filename as String)
print(fileURL.path)
return fileURL.path
}