我需要创建定时器,这将继续运行在后台状态,并将更新用户界面后,应用程序将进入前台状态。最合适的例子是QuizClash应用程序:

我有以下两个想法:
- Create first timer (30 sec interval, non-repeatable)
- Create second timer (0.01 sec interval, repeatable)
- First timer will fire [self timeExiped] method, which will show some UI updates
- Second timer will fire update of ProgressBar on the picture above
- Wrap it all in beginbackgroundTaskWithExpirationHandler method怀疑:如果主计时器在后台状态下过期,将不会显示UI更新(?)
- Start the same timers
- Use encodeRestorableStateWithCoder: to save current timestamp, when entering background
- Use decodeRestorableStateWithCoder: to get difference between saved timestamp and now.
- Invalidate main timer
- Start new main timer with (remains\_seconds - time\_difference\_seconds)怀疑:这甚至是一个可行的选择,因为我没有经验,不能尝试一下吗?
如果你有其他的想法,或者能指出上面描述的2点,我会放一瓶啤酒,如果你曾经在莫斯科:)
发布于 2017-03-16 13:39:52
计时器的目的是什么?
如果要触发UI更改,就没有必要尝试让它“在后台运行”,因为没有需要更新的UI。
任何方法,你几乎肯定想要使用时间戳..。当应用程序返回到前台时,获取上次时间戳以来的运行时间,根据需要更新UI,并重新启动前台活动/更新的计时器。
发布于 2017-03-16 14:27:12
将UIApplicationDidBecomeActive的观察者添加到包含viewWillAppear中的ProgressBar的ViewController中:
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil, using: self.applicationBecameActive)将其放入viewWillAppear中,因为只有当应用程序再次活动时,包含进度条的视图控制器位于堆栈顶部时,applicationBecameActive函数才会触发。
然后在applicationBecameActive方法中,确定ProgressBar的当前进度值应该是什么,相应地进行更新,并重新启动ProgressBar进度。
func applicationBecameActive(notification: Notification){
//determine where the ProgressBar should be
//set the ProgressBar progress value
//restart the ProgressBar progress value updating
}不要忘记删除viewWillDissappear上的观察者:
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)https://stackoverflow.com/questions/42835217
复制相似问题