Search code examples
iosobjective-cgamekit

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?


Solution

  • 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