lu yuan lu yuan - 5 months ago 55
iOS Question

Get the current displaying UIViewController on the screen in AppDelegate.m

The current

UIViewController
on the screen need to response to push-notifications from APNs, by setting some badge views. But how could I get the
UIViewController
in method
application:didReceiveRemoteNotification
: of
AppDelegate.m
?

I tried use
self.window.rootViewController
to get the current displaying
UIViewController
, it may be a
UINavigationViewController
or some other kind of view controller. And I find out that the
visibleViewController
property of
UINavigationViewController
can be used to get the
UIViewController
on the screen. But what could I do if it is not a
UINavigationViewController
?

Any help is appreciated! The related code is as following.

AppDelegate.m

...
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

//I would like to find out which view controller is on the screen here.

UIViewController *vc = [(UINavigationViewController *)self.window.rootViewController visibleViewController];
[vc performSelector:@selector(handleThePushNotification:) withObject:userInfo];
}
...


ViewControllerA.m

- (void)handleThePushNotification:(NSDictionary *)userInfo{

//set some badge view here

}

Answer

You can use the rootViewController also when your controller is not a UINavigationController:

UIViewController *vc = self.window.rootViewController;

Once you know the root view controller, then it depends on how you have built your UI, but you can possibly find out a way to navigate through the controllers hierarchy.

If you give some more details about the way you defined your app, then I might give some more hint.

EDIT:

If you want the topmost view (not view controller), you could check

[[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];

although this view might be invisible or even covered by some of its subviews...

again, it depends on your UI, but this might help...

Comments