Is it possible to refresh a timer in a Today Widget?

回眸只為那壹抹淺笑 提交于 2019-12-09 12:48:30

问题


I was wondering is it possible to update the text label of a timer in a today widget. I took a look around but nothing helped me.


回答1:


Yes you can. I have just tested and it works. You just have to add your timer to the main run loop 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)
    }
}



回答2:


I know this is a Swift question, but I found it looking for Objective-C code and so others may 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
}


来源:https://stackoverflow.com/questions/28012384/is-it-possible-to-refresh-a-timer-in-a-today-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!