Search code examples
iosswifthandlerios8-today-widgettoday-extension

How to update today widget in swift every x seconds


I try to update the content of my today widget extension every x seconds since I try to realize something like a diashow. Therefor I have stored all required data using shared defaults. Loading data from the storage works perfect but the completionHandler of the extension:

    func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
        //I do load the content here 
        completionHandler(NCUpdateResult.NewData)
    }

Is only called once. How can I implement a function that says that "newData" is available every x seconds?


Solution

  • The one way is NSTimer. It is useful for calling method every x seconds.

    var timer : NSTimer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "animateFrame:", userInfo: nil, repeats: true)
    }
    
    func animateFrame(timer: NSTimer) {
        // Do something
    }
    

    In the case, you can call animateFrame: every 3 seconds.