Programmatically Load Controller In App Delegate OSX

In this tutorial I will show you how to programmatically load any NSViewController in your OSX App Delegate. We are using the latest version of Swift as of this article Swift 3.
The reason for this method is that I wanted to load a login controller if the user was not logged into the system.

My controller is named LoginViewController. In story board mode, click on your login controller and give it a story board indentifier loginView pictured below.
Screen Shot 2017-05-21 at 1.44.36 PM
Now that we have an identifier we can now go ahead and switch the controller when needed.
Open AppDelegate and inside the following function

function applicationDidFinishLaunching

Add the following codes

 if(!isUserLoggedIn)
        {
            
            let storyboard = NSStoryboard(name: "Main", bundle: nil)
            
            let controller = storyboard.instantiateController(withIdentifier: "loginView") as! LoginViewController
            
            if let window = NSApplication.shared().mainWindow {
                window.contentViewController = controller
            }
            
            

            
        }

Please keep in mind that this is my example and here I am just checking if the person is logged in to display the controller.
If your storyboard is not named Main then replace with your actual name.
As you can see we use the identifier loginView and I am using my controller named LoginViewController. These of course can be any other name that you are using.

I hope you find this tutorial useful, follow us on Twitter @westernstudios for more.

Please Post Your Comments & Reviews

Welcome to Western Studios

We provide professional website and mobile softwares including Joomla, Wordpress and more.