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

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

    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.

提交回复
热议问题