Pausing iOS game when Notification Center/Control

2019-04-16 16:50发布

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

1条回答
时光不老,我们不散
2楼-- · 2019-04-16 17:53

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];
}
查看更多
登录 后发表回答