Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh Today Widget every time opened

Tags:

swift

I thought that Today View every time when i open it it calls "viewWillAppear" but its not. When i change something in my app, and then I slide down for Today View it sometimes refresh the view and sometimes not.

I do all logic in viewWillAppear (fetch data from coreData and put that data to labels), but its not called everytime.

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

how to call fetchContent and setLabels every time when user opens Today Extensions?

like image 211
Adam Smaka Avatar asked Jan 21 '16 17:01

Adam Smaka


1 Answers

For this matter you should be using NSWidgetProvinding's widgetPerformUpdateWithCompletionHandler.

Steps:

1.- Make sure that your UIViewController implements NCWidgetProviding

class MainViewController: UIViewController, NCWidgetProviding

2.- Add the following function:

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.- In your case you will be using .NewData.

Just make sure that you retrieve needed data and refresh your views (putting every data in place, filling labels, graphs, etc).

Nevermind the fact that your view is not visible during the call to this function, iOS will fill the view and take a snapshot of it.

Then that's what it shows while you are opening notification center and until you gain control again of your app.

So, in your case would be something like this:

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

        completionHandler(NCUpdateResult.NewData)
    }
like image 132
Hugo Alonso Avatar answered Nov 14 '22 05:11

Hugo Alonso