如何每隔x秒在swift中更新今天的小部件

Flo*_*etz 5 handler ios swift ios8-today-widget today-extension

自从我尝试实现类似diashow之类的东西以来,我每隔x秒尝试更新我今天的小部件扩展的内容.因此,我使用共享默认值存储了所有必需的数据.从存储加载数据工作完美但扩展的completionHandler:

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

只被叫一次.如何实现一个每x秒可以使用"newData"的函数?

小智 3

一种方法是 NSTimer。它对于每 x 秒调用一次方法很有用。

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
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以每 3 秒调用一次 animateFrame: 。