我的应用程序暂停或在后台时应该使计时器无效吗?

时间:2017-06-07 15:07:00

标签: swift timer background

我有调度程序每15秒获取一次用户配置文件数据。

class ProfileScheduler: NSObject {

    private var _timer: Timer?

    func start() {
        _timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(self.fetchProfile), userInfo: nil, repeats: true)
    }

    func fetchProfile() {
       print("Update........")
       ProfileManager.getProfileData()
    }

}

每次我的应用程序处于(暂停,背景)模式时,我是否应该使Timer无效?当应用变为(有效)时恢复它。

1 个答案:

答案 0 :(得分:2)

  

每次我的应用程序处于(暂停,后台)模式时,我是否应该使Timer无效?

是。请参阅What to do When Your App is Interrupted Temporarily,其中说明您应该停止计时器和其他定期任务。计时器需要一个活动的运行循环才能工作,因此您应该在应用程序变为非活动状态时停止任何计时器,然后在它再次变为活动状态时重新启动它们。