【发布时间】:2015-02-12 18:58:23
【问题描述】:
我正在尝试创建一个由用户在前台手动启动的 NSTimer,并且正如预期的那样完美运行:
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)
updateCounter() 只是在 UI 中更新 UILabel。
现在我想要实现的是在用户离开应用程序时也让它运行。我用谷歌搜索了一些东西并找到了这段代码(我用 Swift 翻译了):
func applicationDidEnterBackground(application: UIApplication) {
var bgTask = UIBackgroundTaskIdentifier()
bgTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in
UIApplication.sharedApplication().endBackgroundTask(bgTask)
}
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
var vc = TimerViewController()
// Fire some methods
UIApplication.sharedApplication().endBackgroundTask(bgTask)
bgTask = UIBackgroundTaskInvalid
});
}
据我所知,基本上,当应用程序进入后台时,我可以从我的 TimerViewController() 的新实例中触发一些方法,该实例应该在后台阶段处理 NSTimer。
现在这是否意味着我需要使用此 vc 或其他方法中的方法,该方法从前台停止的确切时间开始另一个 NSTimer(因为应用程序进入后台)?
如果是,当用户再次打开应用程序时恢复我的第一个NSTimer(再次表示前台:D)我应该如何表现?停止第二个NSTimer 并使用更新的计数器恢复第一个?
实际上,即使是解决方案的草图也值得赞赏,我只是想弄清楚如何处理这种情况。
进一步的问题:如果上面写的结果是正确的,我该如何管理viewcontroller 的实例以获取timer_value(类似secondsLeft 的令牌)时发生从背景到前景的切换,反之亦然?
【问题讨论】:
-
你有没有尝试使用 [[NSRunLoop currentRunLoop] addTimer:loop forMode:NSRunLoopCommonModes];
标签: ios xcode swift background nstimer