【问题标题】:Timer disrupts when notification center is pulled down in iOS 12在 iOS 12 中下拉通知中心时计时器中断
【发布时间】:2018-08-15 19:06:42
【问题描述】:

所以我正在创建一个具有倒数计时器的应用程序。当应用程序退出时,我使用观察者来了解应用程序是否在后台。如果是,我使计时器无效并将退出时间存储在 userDefaults 中。然后,当应用程序返回前台时,我创建一个新计时器并计算应用程序在后台的时间,并将其从总持续时间中减去,以获得经过的时间。当应用程序进入后台时,我将时间存储在 UserDefaults 中:

 @objc func applicationDidEnterBackground() {
    let defaults = UserDefaults.standard
    let quitTime = Date()
    defaults.set(quitTime, forKey: "quitTimeKey") //Storing the time of quit in UserDefaults
    timer?.invalidate()

}

然后我在应用进入前台时创建一个新的计时器实例:

@objc func appEntersForeground() {
    calculateTimeLeft()
    if (timer == nil)
    {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)
    }

}

然后我检查经过的时间:

func checkElapsedTime() -> Double {
    let currentTime = Date()
    let appQuitTime = UserDefaults.standard.object(forKey: "quitTimeKey") as? Date ?? Date.distantFuture
    let elapsedTime = currentTime.timeIntervalSince(appQuitTime)

    return elapsedTime
}

我也在打印时差:

let timeDifference = checkElapsedTime()
print("timeDifference = \(timeDifference)")

问题:但是,这里有一个问题。当我使用该应用程序时,我向下滑动通知中心并向后滑动不到一秒钟,我得到了几千秒的 timeDifference 读数。

这可能是什么原因?这是 iOS 12 的错误吗?只有当我在应用程序中拉下通知中心时才会发生这种情况。

【问题讨论】:

    标签: ios swift timer notifications


    【解决方案1】:

    好的,我让它工作了。基本上,当您向下滑动通知中心时,您正在调用applicationWillResignActive。因此,我没有调用applicationDidEnterBackground,而是使用applicationWillResignActive 进行通知,它开始正常工作!

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 2018-09-17
      • 1970-01-01
      相关资源
      最近更新 更多