Access to tabbar Controller from AppDelegate

Viewed 2625

I have this situation: enter image description here

How can I access the 3rd Tab bar badge from AppDelegate?

I've used this code:

UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    UIViewController *vc = [[UIViewController alloc] init];
    if ([nonLette isEqualToString:@"0"]) {
        for (vc in tabBarController.viewControllers) {
            if (vc.tabBarItem.tag == 999) {
                vc.tabBarItem.badgeValue = nil;
            }
        }

but the self.window.rootViewController returns "start View" and so does not work.

3 Answers

With the new XCode 11 and Swift 5 this is no longer possible.

Instead you want to do this in SceneDelegate.swift, in particular this function func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

You then want to do something like this.

self.window = self.window ?? UIWindow()//@JA- If this scene's self.window is nil then set a new UIWindow object to it.

        //@Grab the storyboard and ensure that the tab bar controller is reinstantiated with the details below.
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabBarController = storyboard.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController

self.window!.rootViewController = tabBarController //Set the rootViewController to our modified version with the StateController instances
        self.window!.makeKeyAndVisible()

        print("Finished scene setting code")
        guard let _ = (scene as? UIWindowScene) else { return }

Hope this helps for the people using the newer XCode out there. The key here is appDelegate no longer has access to window, the sceneDelegate does. If you try to use appDelegate you will get an error that window no longer exists.

Make sure the identifier is set for the tabBarController in the storyboard so it can find it. You can name it whatever, but just refer to that name in the code here for the withIdentifier function

Related