Powered By Blogger

Saturday, September 18, 2010

CopyDatabaseIfNeeded

- (void) CopyDatabaseIfNeeded
{
    BOOL success = NO;
    NSError *pError;
    NSFileManager *pFileManager = [NSFileManager defaultManager];
    NSArray *pUsrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *pDocsDir = [pUsrDocPath objectAtIndex:0];
    NSString *pDbPath = [pDocsDir stringByAppendingPathComponent:NSLocalizedString(@"appDatabaseName",nil)];
    success = [pFileManager fileExistsAtPath:pDbPath];
   
    if(success){
        if(sqlite3_open([pDbPath UTF8String], &database)!=SQLITE_OK)
            sqlite3_close(database);
        return;
    }
   
    NSString *pDatabasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:NSLocalizedString(@"appDatabaseName",nil)];
    success = [pFileManager copyItemAtPath: pDatabasePath toPath: pDbPath error:&pError];
   
    if(!success)
        NSAssert1(0, @"Failed to copy the database. Errror: %@.", [pError localizedDescription]);
    else{
        if(sqlite3_open([pDbPath UTF8String], &database)!=SQLITE_OK)
        {
            sqlite3_close(database);
        }
    }   
}


Place this code in to your application delegate class file and then call it in the same class at the time of application launching.

No comments:

Post a Comment