Detecting the first ever run of an app

2019-02-05 07:59发布

问题:

I am creating an app in which I have to create a plist when the app launches for the first time. I'm later going to use the plist to store details a user later inputs. How can I detect the first launch of the app? I was experimenting with NSUserDefaults but I think I'm doing something wrong.

回答1:

You can do this with NSUserDefaults. But be careful with the Version Number.

Do the following:

NSString *bundleVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];

NSString *appFirstStartOfVersionKey = [NSString stringWithFormat:@"first_start_%@", bundleVersion];

NSNumber *alreadyStartedOnVersion = [[NSUserDefaults standardUserDefaults] objectForKey:appFirstStartOfVersionKey];
if(!alreadyStartedOnVersion || [alreadyStartedOnVersion boolValue] == NO) {
    [self firstStartCode];
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:appFirstStartOfVersionKey];
}

the selector firstStartCode will only be called on time for each application version on the very first run.

Okay?



回答2:

I like to use NSUserDefaults to store an indication of the the first run.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  
if (![defaults objectForKey:@"firstRun"])
  [defaults setObject:[NSDate date] forKey:@"firstRun"];

[[NSUserDefaults standardUserDefaults] synchronize];

You can then test for it later...

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];        
if([defaults objectForKey:@"firstRun"])           
{
  // do something or not...
}

Taken from: Best way to check if an iPhone app is running for the first time



回答3:

You can use the following:

-(void) firstLaunch {
    //Code goes here
}

-(void) firstLaunchCheck {
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"didLaunchFirstTime"]) {
        [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"didLaunchFirstTime"];
        [self firstLaunch];
    }
}