appfrosch
appfrosch

Reputation: 1376

How to get back to the current window from AppDelegate

In my macOS application, I am following a OAuth-Login procedure. I am authenticating successfully by receiving a code within a url through my custom url, with which I already can get hold of an access_token. I start the login procedure with the simple click of a button in a ViewController.

The system I log in to then answers with my registered custom url scheme, providing me with a code I have to then use to get an access_token with POST request. This access_token than can be used to make api calls.

My Problem now is that lacking knowledge of how to implement other techniques, I am currently doing all the latter procedure within the AppDelegate function application(_ application: NSApplication, open urls: [URL]).

From my limited understanding this is the way to handle this, but now how can I get back from there to get hold of the current view? I am really struggling with the view controller life cycle part of things here I guess...

Upvotes: 1

Views: 630

Answers (2)

appfrosch
appfrosch

Reputation: 1376

OK, found it: since there is no rootViewController in macOS-land as there is with iOS, it works a little different:

in macOS you can get hold of the window currently "under keyboard" like so:

in application(_:open:), where the redirect_uri gets called:

if let viewController = NSApplication.shared.keyWindow?.contentViewController as? ViewController {
    // make changes to the view
}

Upvotes: 0

gkivanov
gkivanov

Reputation: 221

In AppDelegate, you can get a reference to the current window's ViewController as follows. Replace "MainViewController" with the name of the one you use.

iOS Swift:

if let vc = window?.rootViewController as? MainViewController {
    // use `vc` here by calling public functions
    // and accessing public properties
}

macOS Swift:

if let vc = NSApplication.shared.mainWindow?.contentViewController as? MainViewController {
    // use `vc` here by calling public functions
    // and accessing public properties
}

Upvotes: 2

Related Questions