通常我们是通过AppDelegate生命周期来监听APP的不同操作,比如进入后台、从后台进入应用等,但是在UIViewController中没有直接提供进入后台、从后台进入应用的监听方法,因此需要我们在UIViewController的-viewDidLoad方法中添加代码监听notification,方法如下:
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomethingWhenApplicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomethingWhenApplicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; //监听是否重新进入程序.
//挂起程序执行方法
-doSomethingWhenApplicationWillResignActive
//进入程序执行方法
-doSomethingWhenApplicationDidBecomeActive
//在UIViewController 的-dealloc方法中移除监听
[[NSNotificationCenterdefaultCenter]removeObserver:self];
可以根据监听来对UIViewController进行相关操作。