Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSWindow returns nil (NSApplication)

I've come across an issue where I cannot access my app's main window, as it returns nil.

let window = NSApplication.sharedApplication().mainWindow

I've found similar questions:

How to get Main Window (App Delegate) from other class (subclass of NSViewController)?

But doing:

let window = (NSApplication.sharedApplication() as! NSArray).objectAtIndex(0)

Doesn't seem to work either.

Do I have to mess around in Storyboard?

Thanks in advance.

Update:

I'm actually trying to port something from Objective-C.

    NSWindow *mainWindow = [[[NSApplication sharedApplication] windows] objectAtIndex:0];
    NSLog(@"%@", mainWindow.contentViewController);

This returns a proper value, when put in the viewDidLoad() block in a NSViewController, so I'm guessing there is something wrong with NSApplication.sharedApplication().

like image 975
Naoto Ida Avatar asked Jul 17 '15 02:07

Naoto Ida


4 Answers

If your app only contains one window, or always starts with the same window without even removing it from memory, you can use this code:

if let window = NSApp.windows.first {
    window.makeKeyAndOrderFront(self) // Or do something else
}

If you need the window during startup of your app, you should load this code async, like this:

DispatchQueue.main.async {
    if let window = NSApp.windows.first {
        window.makeKeyAndOrderFront(self)
    }
}
like image 174
Ely Avatar answered Nov 02 '22 20:11

Ely


You could do this instead:

   func applicationDidBecomeActive(notification: NSNotification) {

        NSApplication.sharedApplication().mainWindow?.movable = false
    }
like image 24
fredsco Avatar answered Nov 02 '22 21:11

fredsco


It also can return nil if the main app window is not active on macOS. For instance I ran into this when I was making a drag and drop file uploader. If the window was not in the front (on the operating system) it would return nil. The following line of code will activate your app (bring to front)

NSApp.activateIgnoringOtherApps(true)

I also needed a timer to delay my call of mainWindow in my case.

like image 9
quemeful Avatar answered Nov 02 '22 21:11

quemeful


From the docs:

The value in this property is nil when the app’s storyboard or nib file has not yet finished loading. It might also be nil when the app is inactive or hidden.

So, this is a perfectly normal thing to have happen, depending on the circumstances.

like image 1
Ken Thomases Avatar answered Nov 02 '22 21:11

Ken Thomases