Как скопировать базу данных sqlite при запуске приложения в iOS? - программирование
Подтвердить что ты не робот

Как скопировать базу данных sqlite при запуске приложения в iOS?

Я хочу скопировать мою базу данных sqlite из базы данных с последними обновлениями для моего приложения iOS при каждом запуске приложения.

Есть ли способ сделать это?

4b9b3361

Ответ 1

вы можете добавить следующие методы в ваш 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"];
}

и вызовите этот метод в своем завершении с помощью метода запуска [self copyDatabaseIfNeeded]; надеюсь, что это поможет.

Ответ 2

используйте код для копирования базы данных при запуске приложения

в вашем appdelegate.m

в

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

  [self getdatabase];

  return YES;
}

и добавьте функцию ниже в ваш 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);    
}

Ответ 3

попробуйте следующее:

NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *strDocDirectory = [docPath objectAtIndex:0];

    self.strDatabasePath = [strDocDirectory stringByAppendingPathComponent:YOUR_DB];


    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: self.strDatabasePath ] == NO)
    {
        const char *dbpath = [self.strDatabasePath UTF8String];
        sqlite3 *contactDB;


        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS YOUR_Table (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";

            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table");
            }

            sqlite3_close(contactDB);

Ответ 4

Попробуйте это в классе AppDelegate

.h файл

@property(nonatomic, retain) NSString *dbPath;

.m file

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self copyDatabaseIfNeeded];
}
- (void) copyDatabaseIfNeeded
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    dbPath = [self getDBPath];

    BOOL success = [fileManager fileExistsAtPath:dbPath];

    if(!success)
    {
       NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sampleDB.sqlite3"];
       success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
       if (!success)
          NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

/********* Database Path *********/
- (NSString *) getDBPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    return [documentsDir stringByAppendingPathComponent:@"sampleDB.sqlite3"];
}

Он автоматически скопирует, если в приложении не будет базы данных.

Надеюсь, это поможет вам.

Спасибо.

Ответ 5

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

Объявите следующую переменную teo в .h:

sqlite3 *database; 
NSString *databasePath;