在应用程序中以及当应用程序在后台运行时运行计时器 [英] Run timer in app and when app is in background

查看:43
本文介绍了在应用程序中以及当应用程序在后台运行时运行计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在应用程序中以及应用程序在后台时,我需要运行一个计时器.

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

上下文是:如果他在特定的视图控制器上,5 分钟后将被重定向到主视图控制器.如果应用程序停留在后台并进入应用程序,计时器应该重定向他.知道我怎样才能做到这一点吗?

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?

推荐答案

你不能用普通的 NSTimer 做到这一点,因为它不支持背景.然而,使用另一种方法很容易实现.

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.

在您的 AppDelegate 中,您有两种方法.applicationWillResignActiveapplicationDidBecomeActive.在 resign 方法中,您只需要将当前的 NSDate 持久化到 NSUserDefaults 中,然后在 active 方法中,检索它并将其与当前的 NSDate 进行比较> 获取应用处于非活动状态的时间.

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.

代码示例:

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
    }
}

这篇关于在应用程序中以及当应用程序在后台运行时运行计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆