sqlite database update when app version changes on

2019-01-10 15:58发布

I have an app with version 1.0 on app store which uses sqlite database for reading the data.
Now I want to update my version to 1.1 with update in database file.
While using developer certificate when I install app on device it did not update the database as the database file already exist in documents folder so i have to manually delete the app and install it again.
My question is, when any user update the app, will the database also get updated according the current version.
Any suggestions are welcome.
Thanks

3条回答
走好不送
2楼-- · 2019-01-10 16:02

This approach relies on NSUserDefaults. The idea is to get the previous app version number(if exists) from NSUserDefaults and compare it with the current version.

The code performs db upgrade if the previous app version < than current version or if the previous version is nil. It means that this approach can be used even though the app was already published on the AppStore. It will upgrade database to the new version during the app update.

This is a plist file:

enter image description here

There is an array which is composed of the version number and a set of sql queries for the corresponding upgrade version. Suppose that a previous version is 1.2 and the actual version is 1.4 the code perform the upgrade only from the version 1.2 to 1.4. If the previous version is 1.3 and the current 1.4 the code performs upgrade only from 1.3 to 1.4. If the previous version is nil the code performs upgrade to 1.1 then to 1.2 then to 1.3 and finally to 1.4.

NSString * const VERSION_KEY = @"version";

-(void)upgradeDatabaseIfRequired{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *previousVersion=[defaults objectForKey:VERSION_KEY];
    NSString *currentVersion=[self versionNumberString];

    if (previousVersion==nil || [previousVersion compare: currentVersion options: NSNumericSearch] == NSOrderedAscending) {
        // previous < current
        //read upgrade sqls from file
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"UpgradeDatabase" ofType:@"plist"];
        NSArray *plist = [NSArray arrayWithContentsOfFile:plistPath];


        if (previousVersion==nil) {//perform all upgrades
            for (NSDictionary *dictionary in plist) {
                NSString *version=[dictionary objectForKey:@"version"];
                NSLog(@"Upgrading to v. %@", version);
                NSArray *sqlQueries=[dictionary objectForKey:@"sql"];
                while (![DB executeMultipleSql:sqlQueries]) {
                    NSLog(@"Failed to upgrade database to v. %@, Retrying...", version);
                };
            }
        }else{
            for (NSDictionary *dictionary in plist) {
                NSString *version=[dictionary objectForKey:@"version"];
                if ([previousVersion compare: version options: NSNumericSearch] == NSOrderedAscending) {
                    //previous < version
                    NSLog(@"Upgrading to v. %@", version);
                    NSArray *sqlQueries=[dictionary objectForKey:@"sql"];
                    while (![DB executeMultipleSql:sqlQueries]) {
                        NSLog(@"Failed to upgrade database to v. %@, Retrying...", version);
                    };
                }

            }
        }

        [defaults setObject:currentVersion forKey:VERSION_KEY];
        [defaults synchronize];
    }

}


- (NSString *)versionNumberString {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *majorVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return majorVersion;
}
查看更多
干净又极端
3楼-- · 2019-01-10 16:10

I am sure there are many ways to do this (and many ways better then mine as well), but the way that I handle such problems is as follows:

First I define a constant in the first .h file of the app (the one that will load first) to indicate First Time load and set it to 0:

#define FirstTime 0

Now you have to know that I have the intention to save the value of this constant in the Documents folder for future references, therefore I use a Shared Data Instance. In the viewDidLoad I do the following test:

//if first time run of this version
if( [MyDataModel sharedInstance].count < (FirstTime + 1) )
{
    //do what you need to do as the first time load for this version

    [MyDataModel sharedInstance].count++
    //save the count value to disk so on next run you are not first time
    //this means count = 1
}

Now the trick is on your new app version (say 1.1). I change the FirstTime to 2:

#define FirstTime 2

Since the saved First Time value on disc is 1 this means you will be caught by the if statement above, therefore inside it you can do anything you want like delete the old tables and recreate them again with the new formation.

Again not that brilliant, but solves the case!

查看更多
不美不萌又怎样
4楼-- · 2019-01-10 16:24

You can use .plist as well:

- (void)isItTheFirstTimeAfterUpdate {
    NSString *versionnum;
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask,
                                                         YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"yourplist.plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if(![fileManager fileExistsAtPath:path]) {
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"yourplist" ofType:@"plist"];
        [fileManager copyItemAtPath:bundle toPath:path error:&error];
    }

    NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    versionnum = @"";
    //it can be installed by user (for ex. it is 1.3 but first installed), no plist value is set before
    if(([savedStock objectForKey:@"versionnum"]) && (![[savedStock objectForKey:@"versionnum"] isEqualToString:@""])){
        versionnum = [savedStock objectForKey:@"versionnum"];
    }

    //to get the version of installed/updated-current app
    NSString *myversion = [NSString stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]];
    //if no version has been set-first install- or my version is the latest version no need to do sth.
    if ([versionnum isEqualToString:myversion] || [versionnum isEqualToString:@""]) {
        NSLog(@"Nothing has to be done");
    }
    else {
        [self cleanDB];//i have clean tables and create my new db tables maybe logout the user etc.
        [savedStock setObject:[NSString stringWithString:myversion] forKey:@"versionnum"];//setting the new version
        [savedStock writeToFile:path atomically:YES];
    }
}

And you can call the function in application launch or in your main view controller's view controller.. your choice.

hope it helps.

查看更多
登录 后发表回答