0

I have looked at Apple's documentation and searched a lot, but I can't find any code or specific explanation on how to do this.

I want to send data to the widget when users open a specific viewController and then update the widget's view to show the new data.

I have tried:

  1. Adding a notification. (Did not fire in widget code when posted from app)
  2. Having a singleton object in the app and update a property, and fetch data from the widget. (This partially works, but the widget is never updated)

I have handled updating the view in the widget, but this is not called when I want to update the widget (changed some values because of company secrets):

- (void) widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
NSDictionary *data = [[SINGLETON sharedInstance] getData];

if(_data == nil && data == nil) {
    _showData = NO;
    completionHandler(NCUpdateResultNoData);
} else if(_data != nil && [_data isEqual:data]) {
    _showData = YES;
    completionHandler(NCUpdateResultNoData);
} else if(data == nil) {
    _data = nil;
    _showData = NO;
    [self updateView];
    completionHandler(NCUpdateResultNewData);
} else {
    _data = data;
    _showData = YES;
    [self updateView];
    completionHandler(NCUpdateResultNewData);
}
}

[self updateView] is updating the widget's view based on _showData (two different views, one that shows data and one without any data).

Can someone please provide me a simple code example (both app and widget) on how to send data to widget (from host app viewController) and how to update widget's view when data is sent / received?

Otziii
  • 2,304
  • 1
  • 25
  • 34

1 Answers1

2

You can pass data between your app and your widget by storing data in a shared container. Your app could then write data to that container and your widget could read it from there.

Check out this question for example (both the question and the answer). Sharing data between an iOS 8 share extension and main app

Or you can watch this tutorial. https://www.youtube.com/watch?v=h3qUsjUMj74

ObjC tutorial (notice step #5 and further). http://www.glimsoft.com/06/28/ios-8-today-extension-tutorial/

Community
  • 1
  • 1
timaktimak
  • 1,380
  • 1
  • 12
  • 21
  • Thanks! I thought for some reason that you should not use NSUserDefaults (groups) in iOS 10 extensions, the youtube movie was really helpful. – Otziii Dec 15 '16 at 11:12
  • 1
    The YouTube video seems not to be available anymore. Any chance to get it back online? – valeCocoa Aug 28 '17 at 14:01