Notifying a ViewController with UIApplicationDidBecomeActiveNotification

If a running iOS application is switched out for another, its application delegate is notified by calls to the applicationWillResignActive and applicationDidEnterBackground methods. When reactivated, the delegate receives calls to the applicationWillEnterForeground and applicationDidBecomeActive methods. All fairly self explanatory,  except when you need to refresh some data in a UIViewController. As it turns out, there is a fairly straight forward way to handle this using the very handy NSNotificationCenter and UIApplicationDidBecomeActiveNotification

First, attach to the notification in the viewWillAppear method of the target view controller:


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

	[[NSNotificationCenter defaultCenter] addObserver: self
											 selector: @selector( appActivated: )
												 name: UIApplicationDidBecomeActiveNotification
											   object: nil];

}

Next, be a good citizen and remove the observer in the viewWillDisappear method:

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	[[NSNotificationCenter defaultCenter] removeObserver:self ];
}

Finally, implement the appActivated observer method:

- (void)appActivated:(NSNotification *)note
{
	[self update];
}

Set a breakpoint on the appActivated method then fire up the app in the debugger. Double click the home button and switch to another app then double click and switch back to yours. At that point, if everything is configured correctly, you should see the debugger trap on your breakpoint.

Our mobile applications typically do a lot of communicating with webservices. One useful application of this technique we use is to check for network connectivity and make sure that the most current data is currently reflected in the view.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>