IOS开发中如何判断程序第一次启动
在软件下载安装完成后,第一次启动往往需要显示一个新手操作引导,来告诉用户怎么操作这个app,这就需要在程序一开始运行就判断程序是否第一次启动,如果是,则显示新手操作引导节视图,如果不是,则进入其他视图。
可以使用NSUserDefaults这个单例来判断程序是否第一次启动,在
AppDelegate.m这个文件中的didFinishLaunchingWithOptions函数中加入下面这段单例的代码:
// 使用NSUserDefaults来判断程序是否第一次启动 NSUserDefaults *TimeOfBootCount = [NSUserDefaults standardUserDefaults]; if (![TimeOfBootCount valueForKey:@"time"]) { [TimeOfBootCount setValue:@"sd" forKey:@"time"]; NSLog(@"第一次启动"); }else{ NSLog(@"不是第一次启动"); } NSLog(@"启动成功");
加入进去后整个代码是这样的:
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 2 3 4 // 使用NSUserDefaults来判断程序是否第一次启动 5 NSUserDefaults *TimeOfBootCount = [NSUserDefaults standardUserDefaults]; 6 if (![TimeOfBootCount valueForKey:@"time"]) { 7 [TimeOfBootCount setValue:@"sd" forKey:@"time"]; 8 NSLog(@"第一次启动"); 9 }else{ 10 NSLog(@"不是第一次启动"); 11 } 12 13 NSLog(@"启动成功"); 14 15 16 return YES; 17 }
这样当第一次启动的时候显示:
2016-04-28 14:53:37.080 UIAlertController[2614:135823] 第一次启动 2016-04-28 14:53:37.085 UIAlertController[2614:135823] 启动成功
以后启动的时候显示:
2016-04-28 15:06:39.809 UIAlertController[2660:140545] 不是第一次启动 2016-04-28 15:06:39.809 UIAlertController[2660:140545] 启动成功
完。