简体   繁体   中英

Pause NSTimer when app goes to background

I have the following in my touchesBegan function in my GameScene so that the timer only starts when the user touches a certain sprite:

let start = SKAction.runBlock({
    NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "printDuration:", userInfo: NSDate(), repeats: true)
})

tapToStartNode.runAction(start)

and the following function:

func printDuration(timer: NSTimer) {
    if self.view?.paused == false {
        guard let userInfo = timer.userInfo else {
            return
        }
        guard let startDate = userInfo as? NSDate else {
            return
        }
        let duration = NSDate().timeIntervalSinceDate(startDate)
        currentTime = NSDate().timeIntervalSinceDate(startDate)
        currentTimeValueLabel.text = "\(NSString(format:"%3.2f", duration))"
    }
}

However, when applicationDidEnterBackground or applicationWillResignActive the timer is not paused and continues to run when the app is in the backgorund. How do I make it stop?

Here a tips you can use for your problem

You can use func applicationDidEnterBackground(_ application: UIApplication) or func applicationWillResignActive(_ application: UIApplication) on AppDelegate

Access your controller by initialize rootViewController example :

let vc = self.window?.rootViewController as? ViewController

Then you can access your function (make sure function is on public state)

vc.pauseTimer() (customize based on your situation)

Hope it will be helpful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM