Siriss
Siriss

Reputation: 3767

didBecomeActive un-pauses game

I am pausing my game with a willResignActive notification, and it seems to pause the game, but when didBecomeActive is called, it seems to un-pause on its own.

[[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(applicationWillResign)
     name:UIApplicationWillResignActiveNotification
     object:NULL];

- (void) applicationWillResign {

    self.scene.view.paused = TRUE;
    NSLog(@"About to lose focus");
}

How do I get it to stay paused? Do I actually need to pause it in my AppDelegate?

Upvotes: 0

Views: 366

Answers (1)

0x141E
0x141E

Reputation: 12753

Here's a way to keep the view paused after returning from background mode. It's a bit of a hack, but it does work.

1) Define an SKView subclass with a boolean named stayPaused...

    @interface MyView : SKView

    @property BOOL stayPaused;

    @end

    @implementation MyView

    // Override the paused setter to conditionally un-pause the view
    - (void) setPaused:(BOOL)paused
    {
        if (!_stayPaused || paused) {
            // Call the superclass's paused setter
            [super setPaused:paused];
        }
        _stayPaused = NO;
    }

    - (void) setStayPaused
    {
        _stayPaused = YES;
    }

    @end

2) In the storyboard, change the class of the view to MyView

3) In the view controller, define the view as MyView

4) Add a notifier to set the stayPaused flag

    @implementation GameViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];

        // Define view using the subclass
        MyView * skView = (MyView *)self.view;

        // Add an observer for a method that sets the stay pause flag when notified
        [[NSNotificationCenter defaultCenter] addObserver:skView selector:@selector(setStayPaused)
                                                     name:@"stayPausedNotification" object:nil];

        ...

5) In AppDelegate.m, post a notification to set the stay paused flag when the app becomes active

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stayPausedNotification" object:nil];
}

Upvotes: 2

Related Questions