How to copy sqlite database when application is launched in iOS?

Solution 1:

you can add following methods to your appdelegate

- (void) copyDatabaseIfNeeded {

    //Using NSFileManager we can perform many file system operations.
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    NSString *dbPath = [self getDBPath];
    BOOL success = [fileManager fileExistsAtPath:dbPath];

    if(!success) {

       NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database.sqlite"];
       success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

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

- (NSString *) getDBPath
{   
    //Search for standard documents using NSSearchPathForDirectoriesInDomains
    //First Param = Searching the documents directory
    //Second Param = Searching the Users directory and not the System
    //Expand any tildes and identify home directories.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    //NSLog(@"dbpath : %@",documentsDir);
    return [documentsDir stringByAppendingPathComponent:@"database.sqlite"];
}

and call this method in your did finish with launching method [self copyDatabaseIfNeeded]; hope this will help.

Solution 2:

use below code for coping database when application launch

in your appdelegate.m

in

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

  [self getdatabase];

  return YES;
}

and add below function in to your appdelegate.m

-(void)getdatabase
{
    BOOL success;
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DBPath = [pathArray objectAtIndex:0];
    NSString *writableDBPath = @"";
    writableDBPath = [DBPath stringByAppendingPathComponent:@"xyz.sqlite"];
    NSLog(@"writableDBPath:%@",writableDBPath);
    success = [filemanager fileExistsAtPath:writableDBPath];
    if (!success) {
        NSString *defaultDBpath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"xyz.sqlite"];
       success = [filemanager copyItemAtPath:defaultDBpath toPath:writableDBPath error:&error];
       if (!success) {
            NSAssert(0, @"failed to copy database at path with message '%@'.",[error localizedDescription]); 
        }
    }     
    NSLog(@"111writableDBPath:%@",writableDBPath);    
}

Solution 3:

Here it is in Swift 4/5

    func copyDatabaseIfNeeded(sourcePath : String) -> Bool {
      var destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
      destPath = destPath + "/foo.db3"
      let databaseExistsWhereNeeded = FileManager.default.fileExists(atPath: destPath)
      if (!databaseExistsWhereNeeded) {
        do {
            try FileManager.default.copyItem(atPath: sourcePath, toPath: destPath)
            print("db copied")
        }
        catch {
            print("error during file copy: \(error)")
        }
    }
    return true
}