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

时间:2015-08-30 12:22:21

标签: ios swift handler ios8-today-widget today-extension

我尝试每隔x秒更新一次我的小部件扩展程序的内容,因为我尝试实现像diashow这样的东西。因此,我使用共享默认值存储了所有必需的数据。从存储中加载数据是完美的但扩展的completionHandler:

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

只调用一次。如何实现一个每x秒可以使用“newData”的函数?

2 个答案:

答案 0 :(得分:2)

一种方式是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
}

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

答案 1 :(得分:1)

有很多方法可以做到这一点。一种方法是添加观察者。

喜欢这个

NSNotificationCenter.defaultCenter().addObserver(self, selector:"updateStuff", name:
        UIApplicationWillEnterForegroundNotification, object: nil)


func updateStuff() -> Void{

  // Update your Stuff...
}

因此,Selection会在Today Widget类中调用一个函数。

因此当你的更广泛的人进入前景时,你的Widget会调用你的功能。

请注意您的widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void))  是否可以从Web加载内容。比你不需要观察者

我希望我能帮到你