具有预填充的SQLite数据库的iOS船舶应用程序
我想运送我的ios应用程序(用swift编写)与我预填充的sqlite数据库,将通过与服务器同步更新。 在Android中,我可以将数据库从assests文件夹移动到数据库和volla,但在ios我很安静,我怎么能实现这一目标?
谢谢
在iOS中,您可以将数据库添加到项目支持文件中。 这将被添加到二进制文件,然后您可以访问并复制它。
从NSBundle获取预填充数据库的位置:
let databasePath = NSBundle.mainBundle().URLForResource("databaseName", withExtension:"sqlite3");
使用NSFileManager获取文档目录的URL:
//Should have an error pointed in case there is an error. let documentsDirectory = NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain:NSSearchPathDomainMask.UserDomainMask, url:nil, shouldCreate:false, error:nil);
最后复制文件:
if let source = databasePath, destination = documentsDirectory { destination = destination.URLByAppendingPathComponent("database.sqlite3") var result = NSFileManager.defaultManager().copyItemAtURL(source, toURL:destination, error:nil) //Should have an error pointer, check that the result is true. If not check error. }
简单的方法是:+select持久性URL是在你的库文件夹/子文件夹(或文件,如果你想要的)。 +当你实现你的persistentStoreCoordinator时,首先检查.sqlite是否存在于上面的URL。 如果没有,请将.sqlite文件复制到该位置,如果是,则不执行任何操作。 +使用该URL初始化持久存储。
您必须确保.sqlite的数据与数据库模型匹配