自己用swift 写了个计时器,每当app切换后台的时候软件就会暂停,若自己申请后台,则由苹果管理,无法准确计时。
我搜索网上的文章,获得了解决方法。以下是我的解决过程
实现方法:
1.用Notification注册通知
可写在ViewDidLoad里面,我写在了isCounting的计算型属性里面,当停止计时时,清除事件监听,开始计时时注册监听
//监测进入后台
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
//监测程序被激活
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: Notification.Name.UIApplicationDidBecomeActive, object: nil)