Is it possible to update the timer in Today widgets?

I was wondering if it is possible to update the timer text label in today's widget. I looked around, but nothing helped me.

+6
source share
2 answers

Yes, you can. I just tested and it works. You just need to add your timer to the main run cycle of NSRunLoopCommonModes:

RunLoop.main.add(yourTimerName, forMode: .commonModes) 

 import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet weak var strTimer: UILabel! var timer = Timer() func updateInfo() { strTimer.text = Date().description } override func viewDidLoad() { super.viewDidLoad() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateInfo), userInfo: nil, repeats: true) RunLoop.main.add(timer, forMode: .commonModes) } func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) { completionHandler(.newData) } } 
+7
source

I know this is a Swift question, but I found that I was looking for Objective-C code, and others can too.

 -(void) viewDidLoad { [NSTimer scheduledTimerWithTimeInterval:1 // update more than once a second to appear in sync with the system clock target:self selector:@selector(updateUi:) userInfo:nil repeats:YES]; } -(void) updateUi:(NSTimer *)timer { // Update Widget UI as required } 
+3
source

Source: https://habr.com/ru/post/981182/


All Articles