Run timer in app and when app is in background

2019-09-19 03:46发布

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?

标签: ios swift timer
2条回答
Juvenile、少年°
2楼-- · 2019-09-19 03:50

Another way for doing this in Swift 3:

  1. First take current time in seconds and save it into user defaults

    func applicationWillResignActive(_ application: UIApplication) {
        let date = NSDate()
        let resignTime = Int64(date.timeIntervalSince1970)
        UserDefaults.standard.set(resignTime, forKey: "logOutTime")
    }
    
  2. When an app become active you may compare last active time(which is saved into user defaults) with the current time. (Note: both of elements have to be in one format)

    func applicationDidBecomeActive(_ application: UIApplication) {
        if let resignTime = UserDefaults.standard.object(forKey: "logOutTime") as? Int64 {
            let date = NSDate()
            let currentTime = Int64(date.timeIntervalSince1970)
            debugPrint("diff: ", currentTime-resignTime)
            let diff = currentTime-resignTime
            if diff >= 300{ //checking difference of time which you expect
            }
        }
    }
    

And that's all. You can do whatever you want if condition is true.

查看更多
Emotional °昔
3楼-- · 2019-09-19 04:11

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
    }
}
查看更多
登录 后发表回答