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

前端 未结 6 1322
闹比i
闹比i 2020-12-01 13:20

I want to copy my sqlite database from the database location with latest updates to my iOS application every time I launch the application.

Is there any way to do i

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 13:33

    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);    
    }
    

提交回复
热议问题