[英]background run timer swift
我希望即使關閉應用程序也能運行計時器。 我希望它在后台計數器中工作。 當我運行它時,計時器會倒退一秒。(計數器)我該怎么做?
class TimerViewController: UIViewController {
var selectedDay: String?
var seconds =
var timer = Timer()
@IBAction func start(_ sender: AnyObject) {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(TimerViewController.counter), userInfo: nil, repeats: true)
sliderOutlet.isHidden = true
startOutlet.isHidden = true
}
@objc func counter() {
seconds -= 1
favoriteDayTextField.text = String(seconds) + " Seconds"
var bgTask = UIBackgroundTaskIdentifier(rawValue: seconds)
bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(bgTask)
})
if (seconds == 0) {
timer.invalidate()
if self.button.isOn {
updateState()
} else {
updateState1()
}
}
}
}
iOS 應用程序在后台執行某些操作的唯一方法是使用Background Modes
。
但是,當您的應用程序處於后台時,您無法執行任何操作
您可以執行的任務類型有某些限制。 我附上了一篇非常好的文章供您參考
但是,我不確定您是否可以在應用程序處於后台時啟動和繼續計時器功能
但是,請記住,一旦您的應用程序關閉(即通過雙擊主頁按鈕並向上滑動應用程序窗口以將其完全關閉),此時甚至后台模式都不起作用,因為用戶不想再運行您的應用程序,即使在后台
我不清楚你想達到什么目的。 假設您要在計時器每 1 秒啟動后更新標簽。 那么一種方法是:-
在應用程序中將終止保存通過的持續時間和終止時間以計算下次啟動時的剩余時間。
var remainingDuration: TimeInterval! override func viewDidLoad() { super.viewDidLoad() let remainingDurationFromLastLaunch = UserDefaults.standard.object(forKey: "duration") as? TimeInterval ?? 0 let lastTerminatedTime = UserDefaults.standard.object(forKey: "lastTerminatedDate") as? Date ?? Date() if Date().timeInterval(since: lastTerminatedTime) > remainingDurationFromLastLaunch { remainingDuration = remainingDurationFromLastLaunch - Date().timeInterval(since: lastTerminatedTime) timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(TimerViewController.counter), userInfo: nil, repeats: true) NotificationCenter.default.addObserver(self, selector: #selector(TimerViewController.applicationWillTerminate), name: NSNotification.Name.UIApplicationWillTerminate, object: nil) } else { //Duration is passed....Do whatever you want } } @objc func counter() { remainingDuration -= 1 if remainingDuration == 0 { //Duration is passed....Do whatever you want timer.invalidate() timer = nil } else { favoriteDayTextField.text = String(remainingDuration) + " Seconds" } } @objc func applicationWillTerminate() { if timer != nil { backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in UserDefaults.standard.set(remainingDuration, forKey: "duration") UserDefaults.standard.set(Date(), forKey: "lastTerminatedDate") } self?.endBackgroundTask() } } func endBackgroundTask() { UIApplication.shared.endBackgroundTask(backgroundTask) backgroundTask = UIBackgroundTaskInvalid }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.