如何在ios9中检测两次点击主页按钮

时间:2016-08-17 12:24:59

标签: swift ios9 uiapplicationdelegate home-button

在我正在编写以学习 swift 和iOS9的应用中,当用户双击主页按钮并成为应用切换器时,我试图暂停我的NStimer,符合编程ios9 matt neuberg,当用户双击Home按钮时,用户现在可以在app切换器界面中工作。如果您的应用是最重要的,您的应用代理会收到以下消息: applicationWillResignActive

但我的计时器仅在我点按一次主页按钮时暂停,当我点击两次并使用应用程序切换器时,我看到我的计时器计数,任何想法?

1 个答案:

答案 0 :(得分: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)

}