Search code examples
macosswiftnswindow

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().


Solution

  • 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.