How to update today widget in swift every x seconds

Florian Chrometz picture Florian Chrometz · Aug 30, 2015 · Viewed 15k times · Source

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?

Answer

pixyzehn picture pixyzehn · Aug 30, 2015

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.