如何检测在ios9中双击home键



在我的应用程序中,我正在编写学习swift和iOS9,我试图暂停我的NStimer当用户双击home键并成为在应用切换器,根据编程iOS9马特纽伯格,当用户双击home键,用户现在可以在应用切换器界面工作。如果你的应用是最前端的,你的应用委托会收到这个消息:applicationWillResignActive:

但是我的计时器只暂停当我点击home键一次,当我点击两次,有应用程序切换,我看到我的计时器计数,有什么想法吗?

试着在你的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)
}

最新更新