Sqlite3 from Bundle Resources in iOS

做~自己de王妃 提交于 2019-12-08 08:12:50

问题


Hi I'm planning to add a static SQLite3 from my projects resource folder but I dont know if I'm doing it correctly.

so far here's my progress... Created SQLite3 Database from SQLite Database Browser

Copied Sqlite3 Database to my project folder

Added network.db to my project resource folder

and now I don't know where to go next.. I hope someone can help me with my problem.


回答1:


If you are modifying your database at run time (i.e. you are inserting, deleting or updating records), you need to create a copy from bundle to documents directory. iOS sendboxing mechanism will not allow you to modify bundle resource at run time. So, you need to copy it to documents directory. Below code can help you out:

 NSFileManager *fileManager = [NSFileManager defaultManager];
 NSError *error = nil;

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
 NSString *documentsDir = [paths objectAtIndex:0];
 NSString *filePath = [documentsDir stringByAppendingPathComponent:@"network.db"];

 BOOL success = [fileManager fileExistsAtPath:filePath];

 if(!success)
 {
      NSString *defaultDBPath = [[[NSBundle mainBundle] pathForResource:@"network" ofType:@"db"];
      success = [fileManager copyItemAtPath:defaultDBPath toPath:filePath error:&error];

      if (!success)
           NSAssert1(0, @"Failed to create writable resource file with message '%@'.", [error localizedDescription]);

 }

If you are referring your db for lookup purpose only (only using it for select queries), there is no need to copy from bundle to documents directory.




回答2:


You need to add that project file into the documents directory,

You can do this for that,

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponent:@"networks.db"];

NSError *error;

[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:documentsDirectory error:&error];

And then if you want to do anything with the SQLite3 file, you can use any SQLite Managers, For example SQLite Manager




回答3:


check out my answer on this link . this will copy your database into document directory file from your bundle. then you can use this database and insert , update , delete your data. for more info this is the Sample Code



来源:https://stackoverflow.com/questions/23236554/sqlite3-from-bundle-resources-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!