启动通知中心/控制中心时暂停iOS游戏

时间:2014-06-18 17:43:09

标签: nsnotificationcenter

我假设当这类事件发生时,我的应用程序会通过NSNotificationCenter发送通知。有谁知道这些是什么?

1 个答案:

答案 0 :(得分:3)

在我正在处理的应用程序中,我也需要处理这些事件并使用以下两个通知执行此操作:

UIApplicationWillResignActiveNotification >>启动通知中心或控制中心时会触发此通知。

UIApplicationWillEnterForegroundNotification >>解除通知中心或控制中心时会触发此通知。

这些事件当然可以从AppDelegate处理:

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Handle notification
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Handle Notification
}

虽然取决于您的应用,但可能更容易在需要了解此功能的View Controller中显式侦听这些事件:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];

...并实施您的选择器:

- (void)appWillResignActive:(NSNotification *)notification
{
    // Handle notification
}

- (void)appDidBecomeActive:(NSNotification *)notification
{
    // Handle notification
}

最后,当你完成时,将自己当作观察者去除:

- (void)viewWillDisappear:(BOOL)animated
{
    // Remove notifications
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];

    [super viewWillDisappear:animated];
}