Swift中具有背景的计时器

时间:2019-04-29 08:56:34

标签: swift timer

我想做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")
    }
}

1 个答案:

答案 0 :(得分:0)

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

我使用以下代码:

在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")
        }
}