chanpkr
chanpkr

Reputation: 915

Pausing the game when entering background

I'm trying to make my game pause(while saving the current state of the game like timer values and scores) when the user enters the background. I know I have to implement this in

- (void)applicationDidEnterBackground:(UIApplication *)application method

But I have no idea how to. I'm guessing I first have to check if the current view controller the user is currently on is the game scene, and then, if it is, I call the method for pausing. Am I getting the right idea? I don't know how to access the current view controller. Can anyone shed some light?

Upvotes: 1

Views: 325

Answers (2)

RTasche
RTasche

Reputation: 2644

subclass UINavigationController and add the view controller as an observer for UIApplicationDidEnterBackgroundNotification

@interface GameViewController : UIViewController
@end

@implementation GameViewController
- (void) init {
   self = [super init];
   if (self) {
      [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(saveGameState) name: UIApplicationDidEnterBackgroundNotification object: nil];
   }
}

- (void) delloc {
   [[NSNotificationCenter defaultCenter] removeObserver: self name: UIApplicationDidEnterBackgroundNotification object: nil];
}

- (void) saveGameState {
//do the things you neeed to do
}
@end

Upvotes: 2

Jerome Diaz
Jerome Diaz

Reputation: 1866

Your problem is getting your game view controller to know the application will enter background?

When your game view controller appear, use the Notification Center to register it to listen for the UIApplicationDidEnterBackgroundNotification notification

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myBackgroundHanlerMethod:) name: UIApplicationDidEnterBackgroundNotification object:nil];

and handle the notification inside a

- (void)myBackgroundHanlerMethod:(NSNotification *)notification;

Upvotes: 2

Related Questions