Question

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 enter image description here

Added network.db to my project resource folder enter image description here

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

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top