title: How to programmatically open the app window from the background in SwiftUI on macOS (not iOS)?
body: <p>I have a very simple SwiftUI app that runs in the menu bar and should periodically open an app window (there is only one window/view in the whole app) from inside a repeating timer in the background. </p>
  
  <p>How do I actually open the app window from code?</p>
  
  <p>Here's a simplified <code>AppDelegate.swift</code> example showing what I'm trying to do:</p>
  
  <pre><code>import Cocoa
  import SwiftUI
  
  @NSApplicationMain
  class AppDelegate: NSObject, NSApplicationDelegate {  
      var window: NSWindow!
  
      func applicationDidFinishLaunching(_ aNotification: Notification) {
          // Create the SwiftUI view that provides the window contents.
          let contentView = ContentView()
  
          // Create the window and set the content view. 
          window = NSWindow(
              contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
              styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
              backing: .buffered, defer: false)
          window.center()
          window.setFrameAutosaveName("Main Window")
          window.contentView = NSHostingView(rootView: contentView)
          window.makeKeyAndOrderFront(nil)
  
          var loop = 0
          Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
              loop+=1
              if (loop % 10 == 0) {
                  // TODO: How to close the window?
              } else {
                  // TODO: How to reopen the window?
              }
          }
      }
  }
  </code></pre>