【问题标题】:How to update today widget in swift every x seconds如何每 x 秒快速更新今天的小部件
【发布时间】:2015-08-30 12:22:21
【问题描述】:

我尝试每 x 秒更新一次今天的小部件扩展的内容,因为我尝试实现类似 diashow 的功能。因此,我使用共享默认值存储了所有必需的数据。从存储中加载数据工作完美,但扩展的完成处理程序:

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

只调用一次。我怎样才能实现一个函数说“newData”每 x 秒可用?

【问题讨论】:

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


    【解决方案1】:

    一种方法是 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:。

    【讨论】:

      【解决方案2】:

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

      这样

      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 加载内容。比你不需要观察者

      希望能帮到你

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-28
        • 2022-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多