0

I'm developing a app that use a Sqlite3 database. For now the db is inside app package, but I know that I'll have problems to update the data when I test in real world, with a real iPhone.

1 - How can I copy, at bundle phase, my project database to Library folder?

2 - How can I access this copied database? For now my code is:

NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myDatabase.sqlite"];
    BOOL success = [fileMgr fileExistsAtPath:dbPath];

What I'll have to change?

3 - How can I preserve this database (with the user's data) if I update the app?

Thanks in advance! ;)

1 Answer 1

1

You have to copy the database from the Resources folder to Documents folder

sqlite3 *database;
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Lists.db"];
success = [fileManager fileExistsAtPath:writableDBPath];
// The writable database does not exist, so copy the default to the appropriate location.
if(!success)
{
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Lists.db"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        TFLog(@"Failed moving database... %@",[error localizedDescription]);
        return;
    }
}

When you update your app database in your Documents folder will be their you just need to check the condition

     success = [fileManager fileExistsAtPath:writableDBPath];
if it does not exits new database will be copied their.
Just keep in mind database structure is same as before.
Sign up to request clarification or add additional context in comments.

2 Comments

You can also turn on UIFileSharingEnabled so you can copy the file off the iPhone via iTunes.
Thank you! I'm analyzing your code, and I have some questions: First, the code checks if the database exists in resourcePath. Should I verify the Documents folder instead? The DB will be safe in the Documents folder? And where is the statement writableDBPath?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.