如何检测首次启动iOS应用程序的时间?
几乎就是Marc和Chris所说的,虽然我更喜欢在应用程序退出时更改值,以防应用程序的多个区域需要了解它.在代码中:
// -applicationDidFinishLaunching: [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"firstLaunch",nil]]; // to check it: [[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]; // -applicationWillTerminate: [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
我意识到这个问题已经很老了,但是我用它来提出一种在"全新安装"之后检测第一次启动的方法(相对于升级/降级后的第一次启动)并认为我在这里共享代码未来的观众,如果有帮助的话.
// Get current version ("Bundle Version") from the default Info.plist file NSString *currentVersion = (NSString*)[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]; NSArray *prevStartupVersions = [[NSUserDefaults standardUserDefaults] arrayForKey:@"prevStartupVersions"]; if (prevStartupVersions == nil) { // Starting up for first time with NO pre-existing installs (e.g., fresh // install of some version) [self firstStartAfterFreshInstall]; [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:currentVersion] forKey:@"prevStartupVersions"]; } else { if (![prevStartupVersions containsObject:currentVersion]) { // Starting up for first time with this version of the app. This // means a different version of the app was alread installed once // and started. [self firstStartAfterUpgradeDowngrade]; NSMutableArray *updatedPrevStartVersions = [NSMutableArray arrayWithArray:prevStartupVersions]; [updatedPrevStartVersions addObject:currentVersion]; [[NSUserDefaults standardUserDefaults] setObject:updatedPrevStartVersions forKey:@"prevStartupVersions"]; } } // Save changes to disk [[NSUserDefaults standardUserDefaults] synchronize];
我通常在用户默认值中使用app版本号而不是boolean作为firstLaunch值.这样,您就可以区分首次启动新安装和首次启动升级.可能在将来的版本中有用......