3

In my app which am writing to learn swift and iOS9, I'm trying to pause my NStimer when user double click the home button and becomes at app switcher, accoridng to programming ios9 matt neuberg, when The user double-clicks the Home button, The user can now work in the app switcher interface. If your app is frontmost, your app delegate receives this message: applicationWillResignActive:

But my timer only pauses when I tap home button once and when I tap twice and have the app switcher, I see my timer counting, any ideas?

D4ttatraya
  • 3,344
  • 1
  • 28
  • 50
  • 2
    show you code in `applicationWillResignActive ` – Igor Aug 17 '16 at 12:39
  • Shud i include code in applicationWillResi‌​gnActive am just using nsnotification along woth my selector action as written below override func viewDidLoad() { super.viewDidLoad() // pause game when home button tapped twice. NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.pauseGame), name: UIApplicationWillResignActiveNotification, object: nil) } inside pause game func, am caller timer.invalidate() – Steve Reynolds Aug 17 '16 at 13:30

1 Answers1

1

Try to add this lines in your 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)
} 

In addition, set your view controller as the observer to those notifications:

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)

}
EdiZ
  • 441
  • 4
  • 13