3

在我正在编写以学习swift和 iOS9 的应用程序中,当用户双击主页按钮时,我试图暂停我NStimer的应用程序切换器,根据 ios9 matt neuberg 编程,当用户双击主页按钮时,用户现在可以在应用切换界面中工作。如果您的应用程序位于最前面,您的应用程序委托会收到以下消息 applicationWillResignActive

但是我的计时器只在我点击主页按钮一次时暂停,当我点击两次并使用应用程序切换器时,我看到我的计时器正在计数,有什么想法吗?

4

1 回答 1

1

尝试在您的 AppDelegate.swift 中添加以下行:

static let kAppDidBecomeActive = "kAppDidBecomeActive"
static let kAppWillResignActive = "kAppWillResignActive"

func applicationDidBecomeActive(application: UIApplication) {
    // Your application is now the active one
    // Take into account that this method will be called when your application is launched and your timer may not initialized yet
    NSNotificationCenter.defaultCenter().postNotificationName("kAppDidBecomeActive", object: nil)
}

func applicationWillResignActive(application: UIApplication) {
    // Home button is pressed twice
    NSNotificationCenter.defaultCenter().postNotificationName("kAppWillResignActive", object: nil)
} 

此外,将您的视图控制器设置为这些通知的观察者:

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(pauseGame), name: AppDelegate.kAppWillResignActive, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(resumeGame), name: AppDelegate.AppDelegate.kAppDidBecomeActive, object: nil)

}
于 2016-08-31T09:06:33.817 回答