Detecting the first ever run of an app

2019-02-05 07:05发布

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.

3条回答
乱世女痞
2楼-- · 2019-02-05 07:40

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];
    }
}
查看更多
再贱就再见
3楼-- · 2019-02-05 07:43

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

查看更多
你好瞎i
4楼-- · 2019-02-05 07:45

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?

查看更多
登录 后发表回答