起初设置的方法为这个
- (void)applicationWillTerminate:(UIApplication *)application {
// 业务逻辑
}
1
2
3
1
2
3
可是通过测试发现,APP退出的时候并不走这个方法
只要添加观察者才会执行这个方法
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:@"UIApplicationDidEnterBackgroundNotification" object:nil];
1
2
1
2
当我方法名里填applicationWillTerminate的时候,在我点击一次home和两次home的时候都会调用这个方法,两次home则调用两次,没有办法分辨此时我是杀死app还是只是回到后台,因为将方法名设置为另外一个单独的方法
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comeHome:) name:@"UIApplicationDidEnterBackgroundNotification" object:nil];
- (void)comeHome:(UIApplication *)application {
NSLog(@"进入后台");
}
- (void)applicationWillTerminate:(UIApplication *)application {
NSLog(@"程序被杀死");
}
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
这么操作之后,comeHome在点击一次home的时候被调用,applicationWillTerminate在点击两次home杀死APP的时候被调用
//监听是否触发home键挂起程序.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationWillResignActive), name: UIApplicationWillResignActiveNotification, object: nil)
///监听是否重新进入程序程序.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationDidBecomeActive), name: UIApplicationDidBecomeActiveNotification, object: nil)
///监听是否被kill
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationWillTerminate), name: UIApplicationWillTerminateNotification, object: nil)