首页 > 解决方案 > Swift 中带背景的计时器

问题描述

我想做Timer应用程序,启动 Activity 和按 Home 计时器将继续工作需要一段时间,但是当我使用下面的代码时,它在前台正常工作,但是当我按 home 并且它在后台工作时,秒大于 60 并且, 在这种情况下,它给了我奇怪的数字,比如 00:01:75。你知道如何解决这个错误吗?提前致谢。

override func viewDidLoad() {
 super.viewDidLoad()

   NotificationCenter.default.addObserver(self, selector: #selector(pauseWhenBackground(noti:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
   NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(noti:)), name: UIApplication.willEnterForegroundNotification, object: nil)
}

@objc func willEnterForeground(noti: Notification) {
    if let savedDate = UserDefaults.standard.object(forKey: "savedTime") as? Date {
        (diffHrs, diffMins, diffSecs) = AddWorkTime.getTimeDifference(startDate: savedDate)

        self.refresh(hours: diffHrs, mins: diffMins, secs: diffSecs)
    }
}

static func getTimeDifference(startDate: Date) -> (Int, Int, Int) {
    let calendar = Calendar.current
    let components = calendar.dateComponents([.hour, .minute, .second], from: startDate, to: Date())
    return(components.hour!, components.minute!, components.second!)
}

func refresh (hours: Int, mins: Int, secs: Int) {
    self.hrs += hours
    self.min += mins
    self.sec += secs
     self.time.text = String(format: "%02d : %02d : %02d", self.hrs, self.min, self.sec)
     self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(AddWorkTime.updateLabels(t:))), userInfo: nil, repeats: true)

}

@objc func updateLabels(t: Timer) {
    if (self.sec == 59) {
        self.min += 1
        self.sec = 0
    }
    if (self.min == 60) {
        self.hrs += 1
        self.min = 0
    }else{
        self.sec += 1
    }

    self.time.text = String(format: "%02d : %02d : %02d", self.hrs, self.min, self.sec)
}

@objc func pauseWhenBackground(noti: Notification) {
    self.timer.invalidate()
    let shared = UserDefaults.standard
    shared.set(Date(), forKey: "savedTime")
}

func resetContent() {
    self.removeSavedDate()
    timer.invalidate()
    self.time.text = "00 : 00 : 00 "
    self.sec = 0
    self.min = 0
    self.hrs = 0
}

func removeSavedDate() {
    if (UserDefaults.standard.object(forKey: "savedTime") as? Date) != nil {
        UserDefaults.standard.removeObject(forKey: "savedTime")
    }
}

标签: swifttimer

解决方案


确保打开后台模式并在 xCode 中设置所需的值。这很奇怪,但是即使关闭了后台模式,这段代码也可以工作。application.beginBackgroundTask {}在 AppDelegate 中设置后,任何计时器似乎都可以工作。

我使用这段代码:

在 AppDelegate 中添加以下代码:

func applicationDidEnterBackground(_ application: UIApplication) {

    application.beginBackgroundTask {} // allows to run background tasks
}

例如,在您想要的地方调用下面的方法或检查您的计时器。

func registerBackgroundTask() {
    DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime.now() + 5, qos: .background) {
            print("fasdf")
        }
}

推荐阅读