iosstoryboardhome-button

Stop Game App if Home Button clicked iOS


I don't know if by Apple's rules it's necessary to implement that when a user is in the middle of a game, if they click on home button the game pauses and when they click back in game, the game unpauses.

Do I have to click something on storyboard for a home button to appear? I don't know.

Since storyboards has no home button on it so how do I code that when user clicks home button to exit the app, the game pauses. When they return again, the game unpauses.


Solution

  • There are two way to implement it:

    1: use NSNotificationCenter:

    - (void)setupBackgroundNotification {
        // the same to applicationWillEnterForeground:
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(open)
                                                     name: UIApplicationWillEnterForegroundNotification
                                                   object:nil];
    
        //// the same to applicationWillResignActive
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(close)
                                                     name: UIApplicationWillResignActiveNotification
                                                   object:nil];
    }
    
    
    - (void)open {
        NSLog(@"the same to applicationWillEnterForeground");
    }
    
    - (void)close {
        NSLog(@"the same to applicationWillResignActive");
    }
    
    - (void)dealloc {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:applicationWillEnterForeground object:Nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:applicationWillResignActive object:Nil];
    }
    

    2: Use UIApplicationDelegatedelegate Method

    - (void)applicationWillResignActive:(UIApplication *)application
    {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }
    - (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.
    }