【问题标题】:Cannot Pause Game when app is in the Background State应用程序处于后台状态时无法暂停游戏
【发布时间】:2016-08-26 12:43:06
【问题描述】:

这可能是一个非常基本的问题,但我制作了一个简单的游戏,用户可以在其中避开迎面而来的障碍物。当我按下主页按钮时,我的应用仍在后台运行,因此应用音乐继续播放,我的所有 NSTIMERS 继续播放,最终导致游戏角色撞到障碍物。

可以告诉我如何在按下主页按钮或切换到另一个应用程序(游戏处于后台状态)时暂停游戏,然后在应用程序再次处于前台时恢复?

【问题讨论】:

  • 请确保您阅读此内容并尝试改进您的问题:stackoverflow.com/help/mcve
  • 到底有什么不正确的地方?
  • @1QuickQuestion 我认为他想了解有关您的代码的更多信息。无论如何我留下了一个答案,看看它是否可以帮助你。

标签: objective-c uiapplicationdelegate uiapplication


【解决方案1】:

我不知道您的代码是如何编写的,但是当用户将应用程序置于后台时,您可以在 AppDelegate.m 中使用此方法来了解确切的时间:

- (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");
}

在该方法内部,您可以将音乐设置为停止并设置所有 NSTIMERS。你可以使用这个:

- (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");
}

知道用户何时从后台回到前台。

【讨论】:

  • 谢谢 J,这很有帮助,但实际上我的 appDelegate 中有类似的东西。我的问题是我想在“NSLog(@"going to background");”处调用一个方法来暂停游戏。指向并在“NSLog(@"Back from Foreground");”处继续。
  • 哦,我明白了。我看到你已经接受了一个答案。太好了:)
【解决方案2】:

很简单...

使用此代码:

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

把它放在包含你的定时器和方法的.m文件的setup方法中。




把它也放在 .m 文件中

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

}

最后一种方法:
-(void)pauseGameSoUserDoesNotDieForNoReason:(NSNotification*)theNotification
是您放置暂停代码的位置。

注意:

此代码可以放在多个 .m 文件中。

【讨论】:

  • 你是一个救生员!谢谢!我认为这是一个非常简单的解决方案!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 2021-08-09
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
相关资源
最近更新 更多