每次打开时刷新今日小部件

时间:2016-01-21 17:07:24

标签: swift

我认为每天当我打开它时,它会调用" viewWillAppear"但事实并非如此。当我在我的应用程序中更改某些内容,然后我向下滑动今天查看它有时会刷新视图,有时不会。

我在viewWillAppear中执行所有逻辑(从coreData获取数据并将该数据放到标签中),但不是每次都调用它。

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    fetchContent()
    setLabels()
    setContentHeight()
    tableView.reloadData()
    print("view will appear")
}

每次用户打开Today Extensions时如何调用fetchContent和setLabel?

2 个答案:

答案 0 :(得分:11)

对于此问题,您应该使用NSWidgetProvinding' widgetPerformUpdateWithCompletionHandler

步骤:

1.-确保您的UIViewController实施NCWidgetProviding

class MainViewController: UIViewController, NCWidgetProviding

2.-添加以下功能:

func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
        // Perform any setup necessary in order to update the view.

        // If an error is encountered, use NCUpdateResult.Failed
        // If there's no update required, use NCUpdateResult.NoData
        // If there's an update, use NCUpdateResult.NewData

        completionHandler(NCUpdateResult.NewData)
    }

3.-在您的情况下,您将使用.NewData

只需确保检索所需数据并刷新视图(将每个数据放在适当位置,填写标签,图表等)。

在调用此函数期间,不要看到您的视图不可见,iOS将填充视图并拍摄快照。

然后在您打开通知中心时显示的内容,直到您再次获得对应用的控制权。

  

所以,在你的情况下会是这样的:

func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
        fetchContent()
        setLabels()
        setContentHeight()
        tableView.reloadData()

        completionHandler(NCUpdateResult.NewData)
    }

答案 1 :(得分:1)

Swift 2.1&& Xcode 7.2 当您多次重新编译今天的扩展时,看起来会出现一些错误。解决方案是从通知中心删除并再次添加。然后它每次打开都刷新