Get the current view controller from the app delegate
Asked Answered
M

12

31

i am new to ios. I need to know the current view controller from app delegate.. i have no idea about this and i don't knowto implement this. i am using this code toimplemnt this but it return null values. I followed this link- Get current view controller from the app delegate (modal is possible) need help.

Moll answered 18/7, 2014 at 12:31 Comment(1)
are you using navigation controller? else post your code to understand betterDescombes
S
61

This is what I use for finding the current view controller that the user is most likely interacting with:

UIViewController+Utils.h

#import <UIKit/UIKit.h>

@interface UIViewController (Utils)

+(UIViewController*) currentViewController;

@end

UIViewController+Utils.m

#import "UIViewController+Utils.h"

@implementation UIViewController (Utils)

+(UIViewController*) findBestViewController:(UIViewController*)vc {

    if (vc.presentedViewController) {

        // Return presented view controller
        return [UIViewController findBestViewController:vc.presentedViewController];

    } else if ([vc isKindOfClass:[UISplitViewController class]]) {

        // Return right hand side
        UISplitViewController* svc = (UISplitViewController*) vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.viewControllers.lastObject];
        else
            return vc;

    } else if ([vc isKindOfClass:[UINavigationController class]]) {

        // Return top view
        UINavigationController* svc = (UINavigationController*) vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.topViewController];
        else
            return vc;

    } else if ([vc isKindOfClass:[UITabBarController class]]) {

        // Return visible view
        UITabBarController* svc = (UITabBarController*) vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.selectedViewController];
        else
            return vc;

    } else {

        // Unknown view controller type, return last child view controller
        return vc;

    }

}

+(UIViewController*) currentViewController {

    // Find best view controller
    UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [UIViewController findBestViewController:viewController];

}

@end

Then whenever I need the current view controller from anywhere in the app simply use:

[UIViewController currentViewController]
Shelbashelbi answered 18/7, 2014 at 12:49 Comment(0)
S
16

Here're some class/static functions in swift that I keep in a Utility class and can help you:

// Returns the most recently presented UIViewController (visible)
class func getCurrentViewController() -> UIViewController? {

    // If the root view is a navigation controller, we can just return the visible ViewController
    if let navigationController = getNavigationController() {

        return navigationController.visibleViewController
    }

    // Otherwise, we must get the root UIViewController and iterate through presented views
    if let rootController = UIApplication.shared.keyWindow?.rootViewController {

        var currentController: UIViewController! = rootController

        // Each ViewController keeps track of the view it has presented, so we
        // can move from the head to the tail, which will always be the current view
        while( currentController.presentedViewController != nil ) {

            currentController = currentController.presentedViewController
        }
        return currentController
    }
    return nil
}

// Returns the navigation controller if it exists
class func getNavigationController() -> UINavigationController? {

    if let navigationController = UIApplication.shared.keyWindow?.rootViewController  {

        return navigationController as? UINavigationController
    }
    return nil
}
Sussi answered 23/4, 2015 at 21:42 Comment(2)
I used this successfully with modifications to get it to compile. Some re-arranging required.Doug
@alaxandermiller, how can i use these to get the viewcontroller names as a String?Togs
S
9

Swift version of jjv360's great answer, (I got rid of some redundant returns, and I think Swift is more readable)

func getCurrentViewController(_ vc: UIViewController) -> UIViewController? {
    if let pvc = vc.presentedViewController {
        return getCurrentViewController(pvc)
    }
    else if let svc = vc as? UISplitViewController, svc.viewControllers.count > 0 {
        return getCurrentViewController(svc.viewControllers.last!)
    }
    else if let nc = vc as? UINavigationController, nc.viewControllers.count > 0 {
        return getCurrentViewController(nc.topViewController!)
    }
    else if let tbc = vc as? UITabBarController {
        if let svc = tbc.selectedViewController {
            return getCurrentViewController(svc)
        }
    }
    return vc
}

From you AppDelegate,

    guard let rvc = self.window?.rootViewController else {
        return
    }
    if let vc = getCurrentViewController(rvc) {
        // do your stuff here
    }
Sherr answered 7/2, 2016 at 15:39 Comment(0)
P
6

This helped me to find the visible view controller. I searched for existing methods and didn't find any. So I wrote my own custom one.

-(id)getCurrentViewController
{
    id WindowRootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

    id currentViewController = [self findTopViewController:WindowRootVC];

    return currentViewController;
}

-(id)findTopViewController:(id)inController
{
    /* if ur using any Customs classes, do like this.
     * Here SlideNavigationController is a subclass of UINavigationController.
     * And ensure you check the custom classes before native controllers , if u have any in your hierarchy.
    if ([inController isKindOfClass:[SlideNavigationController class]])
    {
        return [self findTopViewController:[inController visibleViewController]];
    }
    else */
    if ([inController isKindOfClass:[UITabBarController class]])
    {
        return [self findTopViewController:[inController selectedViewController]];
    }
    else if ([inController isKindOfClass:[UINavigationController class]])
    {
        return [self findTopViewController:[inController visibleViewController]];
    }
    else if ([inController isKindOfClass:[UIViewController class]])
    {
        return inController;
    }
    else
    {
        NSLog(@"Unhandled ViewController class : %@",inController);
        return nil;
    }
}

And sample use :

-(void)someMethod
{
    id currentVC = [self getCurrentViewController];
        if (currentVC)
        {
            NSLog(@"currentVC :%@",currentVC);
        }
}
Pinball answered 12/11, 2015 at 15:22 Comment(0)
A
5

It depends on how you set up your UI. You can possibly get your rootViewController and move through the hierarchy if it is set up in such a way.

UIViewController *vc = self.window.rootViewController;
Annulose answered 18/7, 2014 at 12:40 Comment(2)
i get the view controller name like this way- last view controller is vc== <ViewController: 0x8d52290> but i want the name of the view controller.Moll
If ur following this and u want the name of the controller then try id vc = self.window.rootViewController; NSLog(@"Controller Name : %@", [vc class]);Pinball
S
4
UIViewController* actualVC = [anyViewController.navigationController.viewControllers lastObject];
Sideman answered 18/7, 2014 at 12:46 Comment(0)
B
4

Swift solution For iOS 13+ We have SceneDelgate and multiple windows so you need to use the following code:

private func getCurrentViewController() -> UIViewController? {
    if let rootViewController = UIApplication.shared.windows.first?.rootViewController {
        
        if let presentedViewController = rootViewController.presentedViewController {
            return presentedViewController
        }
        
        return rootViewController
    }
    
    return nil
} 
Burny answered 11/8, 2021 at 13:26 Comment(0)
B
3

I get the root controller and then iterate through presented VC's:

 UIViewController *current = [UIApplication sharedApplication].keyWindow.rootViewController;

while (current.presentedViewController) {
    current = current.presentedViewController;
}
//now you can use current, for example to present an alert view controller:
[current presentViewController:alert animated:YES completion:nil];
Baumgardner answered 12/3, 2016 at 2:20 Comment(0)
K
2

|*| Get Visible View Controller from Navigation View Controller

let NavVccVar = UIApplication.sharedApplication().keyWindow?.rootViewController as! UINavigationController
let ShnSrnVar = NavVccVar.visibleViewController

|*| Presenting from the Visible View Controller

let NavVccVar = UIApplication.sharedApplication().keyWindow?.rootViewController as! UINavigationController
NavVccVar.visibleViewController!.presentViewController(NamVccVar, animated: true, completion: nil)
Krall answered 12/11, 2016 at 19:53 Comment(0)
H
2

This is the best solution that I have tried out yet

+ (UIViewController*) topMostController
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}
Hardcastle answered 23/11, 2016 at 9:54 Comment(0)
M
0

i am using this code-

//in AppDelegate:

@interface AppDelegate()

{

    id lastViewController;

}


@implementation AppDelegate

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions

{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCurrentViewController) name:@"CurrentViewController" object:nil];


}

-(void)handleCurrentViewController:(NSNotification *)notification
 {

    if([[notification userInfo] objectForKey:@"lastViewController"])
   {

        lastViewController = [[notification userInfo] objectForKey:@"lastViewController"];

    }
}

-(void)applicationDidEnterBackground:(UIApplication *)application
{  

    NSLog(@"last view controller is %@", [(UIViewController *)lastViewController class]);

}

@end

//in every ViewController you want to detect

@implementation SomeViewController

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

    [[NSNotificationCenter defaultCenter] postNotificationName:@"CurrentViewController" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:self, @"lastViewController", nil]];

}
Moll answered 18/7, 2014 at 12:48 Comment(0)
C
0

I found this and it works great for me for all types of segues and view controllers. It's very simple and short too which is nice.

+(UIViewController*) getTopController{ UIViewController *topViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

while (topViewController.presentedViewController) {
    topViewController = topViewController.presentedViewController;
}

return topViewController; }
Charland answered 12/1, 2017 at 22:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.