How do I access my viewController from my appDelegate? iOS

IosUiviewcontrollerUikitStoryboard

Ios Problem Overview


I have an iOS app I created as a "view-based app" in xCode. I have only one viewController, but it is displayed automatically, and I see no code that ties it to my appDelegate. I need to pass data from my appDelegate to my viewController, but don't know how to pull that off.

My app delegate.h:

#import <UIKit/UIKit.h>


@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSDictionary *queryStrings;

@end

Also, appDidFinishLoadingWithOptions:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [[JMC sharedInstance] configureJiraConnect:@"https://cmsmech.atlassian.net/"           projectKey:@"WTUPLOAD" apiKey:@"7fc060e1-a795-4135-89c6-a7e8e64c4b13"];
    
    if ([launchOptions objectForKey:UIApplicationLaunchOptionsURLKey] != nil) {
        NSURL *url = [launchOptions objectForKey: UIApplicationLaunchOptionsURLKey];
        NSLog(@"url received: %@", url);
        NSLog(@"query string: %@", [url query]);
        NSLog(@"host: %@", [url host]);
        NSLog(@"url path: %@", [url path]);
        queryStrings = [self parseQueryString:[url query]];
        NSLog(@"query dictionary: %@", queryStrings);
    }
    else {
        queryStrings = [self parseQueryString:@"wtID=nil"];
    }
       
    return YES;
}

Ios Solutions


Solution 1 - Ios

You can access it with:

MyViewController* mainController = (MyViewController*)  self.window.rootViewController;

If you are nesting your view behind a tabviewcontroller or navigation controller it will return that to you and you will need to access your view controller inside of it

Solution 2 - Ios

How about using good old fashioned NSNotifications to send a message from your app delegate to anyone listening (e.g. your view contorller) that something needs to be updated? or you can use Key Value Observing so your view controller can be watching some property in your app delegate.

Solution 3 - Ios

Since you only have one view controller, the generic way (independent of how your app was set up):

UIViewController *vc = [[[UIApplication sharedApplication] keyWindow] rootViewController];

Solution 4 - Ios

If you want to get any other UIViewController, not just the rootViewController:

UIWindow *window=[UIApplication sharedApplication].keyWindow;
UIViewController *root = [window rootViewController];
            
UIStoryboard *storyboard = root.storyboard;
CustomViewController *vcc =(CustomViewController *) [storyboard instantiateViewControllerWithIdentifier:@"storyBoardID"];

Solution 5 - Ios

Swift way to do it, you can call this from anywhere, not just appdelegate:

/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
public var topMostVC: UIViewController? {
    var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while let pVC = presentedVC?.presentedViewController {
        presentedVC = pVC
    }
    
    if presentedVC == nil {
        print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
    }
    return presentedVC
}

Its included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions

Solution 6 - Ios

If you used the View-Based Application template, the single view controller should be accessible via a property in your app delegate. It's the same view controller that gets set as the root view controller of the navigation controller.

If for some reason your project was set up differently, you can get the root view controller of the window, which should be the navigation controller, and then get its top view controller.

EDIT: So the issue is this: With iOS5 and storyboards, Apple has abstracted a lot of the initial set up that you used to have access to (and still do if you opt out of storyboards). They've altered the arguments passed to main() and do more of the set up in the storyboard (which is really just a nib). IMHO, this is in part to keep people from overloading the AppDelegate with heavy operations, like it appears you are doing in yours. The AppDelegate, in essence, exists to manage the Application lifecycle. It's not really meant to be performing methods that hand off information to your view controllers. It's your view controller's job, really, to do the heavy lifting to provide itself with data. I would suggest moving the code into your view controller, perhaps in viewDidLoad. If you need to know the result of the launchOptions objectForKey test it appears you're doing, you could very simply create a property on your AppDelegate, say BOOL launchOptionsURLKeyExists, and set it appropriately. Then you just grab the value of this property in your view controller. You AppDelegate is already a singleton, so you can access it either by [UIApplication sharedApplication].delegate

EDIT 2: viewWillAppear/viewDidAppear gets called when the view is added to the UIApplicationDidEnterForegroundNotification notification in your view controller and respond appropriately when that message is posted.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHackyStackView Question on Stackoverflow
Solution 1 - IosutahwithakView Answer on Stackoverflow
Solution 2 - IosMichael DautermannView Answer on Stackoverflow
Solution 3 - IosConrad ShultzView Answer on Stackoverflow
Solution 4 - IosArben PnishiView Answer on Stackoverflow
Solution 5 - IosEsqarrouthView Answer on Stackoverflow
Solution 6 - Iosjmstone617View Answer on Stackoverflow