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

前端 未结 6 1298
闹比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:39

    -(void)openDatase{  
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
        NSString *documentsDirectory = [paths objectAtIndex:0];  
        self.databasePath = [documentsDirectory stringByAppendingPathComponent:@"weightCal.sqlite"];  
        if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {  
            NSLog(@"Database Successfully Opened ");  
        } else {   
            NSLog(@"Error in opening database ");  
        }  
    }
    
    -(void)dealloc{
        sqlite3_close(database);
        [super dealloc];
    }
    
    
    -(void)copyDatabase {
        BOOL success;
        NSFileManager *fileManager=[NSFileManager defaultManager];
        NSError *error;
        NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory=[paths objectAtIndex:0];
        NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"test.sqlite"];
        success = [fileManager fileExistsAtPath:writablePath];
        if(success) {
           return;
        }
        NSString *defaultPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.sqlite"];
        success=[fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
        if(!success){
           NSAssert1(0,@"Failed to create writable database file with message '%@' .",[error localizedDescription]);
        }
    }
    

    Declare following teo variable in .h:

    sqlite3 *database; 
    NSString *databasePath;
    

提交回复
热议问题