I've implemented a Notification Center Extension that provides a button to launch its containing app. Depending on the state of the widget I want to navigate to one of two different locations in the app when this button is pressed. I was able to obtain this behavior and it works well while the app is in memory, however, if the app has to be launched for the first time when this button is pressed it does not navigate to the correct location.
I know the reason why this occurs. When I parse the URL to determine where to go in the app delegate, I post a notification and provide information in the userInfo
dictionary. I subscribe to this notification in the View Controller that needs to update its UI based on the information in the userInfo
dictionary. The problem is, I subscribe to this notification in viewWillAppear
. This notification is posted before viewWillAppear
is called on this View Controller when the app is launched for the first time, therefore the UI does not update and it behaves as if the app was launched from the home screen.
My question is, is there a different method I can place the code to subscribe to this notification that's early enough in the lifecycle, or is there a better approach to respond to launching from a URL scheme?
Some simplified code:
//AppDelegate.m:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
if ([[url scheme] isEqualToString:@"app name"]) {
if ([[url resourceSpecifier] isEqualToString:@"//tab1"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:DidLaunchWithURLScheme object:nil userInfo:@{@"info": @"first"}];
} else if ([[url query] isEqualToString:@"//tab2"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:DidLaunchWithURLScheme object:nil userInfo:@{@"info": @"second"}];
}
return YES;
}
return NO;
}
//viewWillAppear in View Controller:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didLaunchAppWithURLInfo:)
name:DidLaunchWithURLScheme
object:nil];
- (void)didLaunchAppWithURLInfo:(NSNotification *)notification {
//does get called if app was already in memory
//does not get called if app was fresh launched
//do something here like select a different tab based on the userInfo
}