Reputation: 748
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?
Upvotes: 1
Views: 103
Reputation: 1345
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.
Upvotes: 1
Reputation: 491
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.
This code can be placed in several .m files.
Upvotes: 0