minimartieni minimartieni - 2 months ago 7
Swift Question

Run timer in app and when app is in background

I need to run a timer when the user is in app and also when the app is in background.

The context is: if he is on a specific view controller, after 5 min will be redirected to main view controller. The timer should redirect him if the app stays in background and enters the app. Any idea how can i achieve this?

Answer

You can't do this with a normal NSTimer as there is no support for backgrounding. It is however achievable very easily using another method.

In your AppDelegate you have two methods. applicationWillResignActive and applicationDidBecomeActive. In the resign method you simply need to persist the current NSDate into the NSUserDefaults and in the active method, retrieve it and compare it against the current NSDate to get the amount of time the app was inactive for.

Code examples:

func applicationWillResignActive(application: UIApplication) {
    let date = NSDate()
    NSUserDefaults.standardUserDefaults().setObject(date, forKey: "DateTimer")
}

func applicationDidBecomeActive(application: UIApplication) {
    if let persistedDate = NSUserDefaults.standardUserDefaults().objectForKey("DateTimer") as? NSDate {
        let difference = NSCalendar.currentCalendar().components([.Second], fromDate: persistedDate, toDate: NSDate(), options: [])
        let differenceSeconds = difference.second
    }
}