5

I created a today extension for my iOS App. My app is fetching new datas in background and saving it into a shared database in the app group.

How I can make (if it's possible) the extension to update it's view when background fetches of the main app are performed ? If it's not possible, how I can make something equivalent (like regularly updating the extension to check for new datas in the shared database).

ThibaultV
  • 529
  • 1
  • 5
  • 24

2 Answers2

13

You can use shared NSUserDefaults and observer it.

In your app:

After you update database, execute the below:

NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.yourcompany.sharedDefaults"];
[userDefaults setObject:[NSDate date] forKey:@"updatedDate"];
[userDefaults synchronize];


In your Today Widget:

add a observer in viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(userDefaultsDidChange:)
                                             name:NSUserDefaultsDidChangeNotification
                                           object:nil];

then

- (void)userDefaultsDidChange:(NSNotification *)notification {
    // check updatedDate and update widget UI
}

refer: http://www.glimsoft.com/06/28/ios-8-today-extension-tutorial/

scottphc
  • 954
  • 7
  • 16
  • Thanks ! I saw this tutorial but not the interesting part for me... Shame on me !!! – ThibaultV Oct 22 '14 at 13:34
  • Doesn't the addObserver method get called too many times? each time the viewDidLoad is invoked, without ever dismissing the observer? – Gabriel May 10 '15 at 13:10
  • The viewDidLoad get called only once. And you need to remove observer in the dealloc method. – scottphc May 10 '15 at 13:14
  • According to this http://stackoverflow.com/questions/26523460/today-extension-view-flashes-when-redrawing the viewDidLoad function gets called every time the user pulls the widget drawer. Does the system also create a new instance of the widget? or only recomputes the view? – Gabriel May 10 '15 at 15:46
  • Create a new instance. – scottphc May 10 '15 at 15:57
1

The system create the ViewController every time, but your singleton-instance in your today widget code keep living during a long period.

ivanC
  • 43
  • 7