1

This may be a really basic question, but I have made a simple game in which the user avoids oncoming obstacles. When I press the home button my app is still running in the background, and because of this the app music continues playing and all my NSTIMERS continue which eventually causes the game character to hits an obstacle).

Can show me how to pause the game when I press the home button or switch to another app (game is in the background state), then resume when the app is in the foreground again?

1QuickQuestion
  • 729
  • 2
  • 9
  • 25

2 Answers2

1

I don't know how you have been doing your code, but when the user put the app in background you can use this method in AppDelegate.m to know the exact moment:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    NSLog(@"going to background");
}

Inside of the method you can set your music to stop and set all the NSTIMERS. And you can use this one:

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

    NSLog(@"Back from Foreground");
}

To know when the user come back from the background to the foreground.

Cœur
  • 37,241
  • 25
  • 195
  • 267
J. Lopes
  • 1,336
  • 16
  • 27
  • Thanks J, this was helpful but I actually have something similar to this in my appDelegate. My issue is that I want to call a method to pause the game at the "NSLog(@"going to background");" point and resume at the point of "NSLog(@"Back from Foreground");". – 1QuickQuestion May 02 '16 at 01:08
  • Oh I got it. I saw you have accepted an answer. That's great :) – J. Lopes May 02 '16 at 11:34
0

It's Quite Simple...

Use this code:

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

Put it in the setup method of .m file that contains your timers and the method.




Put this in the .m file as well

-(void)pauseGameSoUserDoesNotDieForNoReason:(NSNotification*)theNotification{

}

This last method:
-(void)pauseGameSoUserDoesNotDieForNoReason:(NSNotification*)theNotification
Is where you put your pausing code.

Note:

This code can be placed in several .m files.

Pro Blaster
  • 491
  • 3
  • 9