Pausing iOS game when Notification Center/Control Center is launched

白昼怎懂夜的黑 提交于 2019-12-12 09:27:40

问题


I’m assuming my app is sent notifications through NSNotificationCenter when these kind of events happen. Does anyone know what these are?


回答1:


In the app I'm working on I needed to handle these events as well and did so using the following two notifications:

UIApplicationWillResignActiveNotification >> This notification is fired when the Notification Center or Control Center is brought up.

UIApplicationWillEnterForegroundNotification >> This notification is fired when the Notification Center or Control Center is dismissed.

These events can naturally be handled from the AppDelegate:

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

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

Though depending on your app it will likely be easier to explicitly listen for these events in the View Controller(s) that needed to be aware of this:

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

... and implement your selectors:

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

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

And lastly remove yourself as an observer when you're done:

- (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];
}


来源:https://stackoverflow.com/questions/24291897/pausing-ios-game-when-notification-center-control-center-is-launched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!