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

Viewed 198491

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 methodapplication: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

}
20 Answers

Regarding NSNotificationCenter Post above (sorry can't find out where to post a comment under it...)

In case some were getting the -[NSConcreteNotification allKeys] error of sorts. Change this:

-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo

to this:

-(void)didReceiveRemoteNotification:(NSNotification*)notif {
NSDictionary *dict = notif.userInfo;
}

Always check your build configuration if you you are running your app with debug or release.

IMPORTANT NOTE: You can't be able to test it without running your app in debug mode

This was my solution

In Swift, just add this single line of code to your BaseViewController to log your displayed view controllers

override public func viewDidLoad() {

super.viewDidLoad()

print("Current ViewController ‍♂️  #\(UIApplication.getTopViewController()?.classForCoder ?? self.classForCoder)")

}

Related