1
votes

Good Day, When I close my MacOS app by using the red button (located at the top left corner), the MacOS application disapears but the dock icon is still there at the bottom. If I click right on the dock icon I want to add a "Re-Open" menu item to re-open the app. Below is the code produced to a certain point... When I click on "Re-Open" it prints "XXX" in the console... because I have not found the code to re-open the app! Any help would be much appreciated to fill up the below function call reOpen(sender : NSMenuItem) Thanks

Below is my AppDelegate.swift file content:

import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  var window: NSWindow!

  func applicationDidFinishLaunching(_ aNotification: Notification) {

    let contentView = ContentView()

    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)
  }

  func applicationWillTerminate(_ aNotification: Notification) {
    // Insert code here to tear down your application
  }

  func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
    let menu = NSMenu()
    let reOpenMenuItem = NSMenuItem(title:"Re-Open", action:#selector(AppDelegate.reOpen), keyEquivalent:"")
    menu.addItem(reOpenMenuItem)
    return menu
  }

  @objc func reOpen(sender : NSMenuItem) {
    print("XXX")
  }
}
1
Does the app quit when you close the window? Do you want to restart the running app?Willeke
When I click on the window top left red button, the window disappears (does it quit or close?) but the top app menu bar stays until we do not touch any other app windows. Now with the final code I can right click on the dock icon and click on the added menu item called "Re-Open" to re-open the App. This is what I wanted.Wild8x
The red dot closes the window, the app is still running. The answer is to the question "How to use the MacOS app dock menu to restart the app?".Willeke
Thanks Willeke for informing me that the red does not close the App. I realize that the code I am using is "too much" because it re-start the app but I could not find the code that simply re-open the window...Wild8x

1 Answers

3
votes

Finally the final working code to add for the reOpen function is:

@objc func reOpen(sender : NSMenuItem) {
  print("XXX")
  let url = URL(fileURLWithPath: Bundle.main.resourcePath!)
  let path = url.deletingLastPathComponent().deletingLastPathComponent().absoluteString
  let task = Process()
  task.launchPath = "/usr/bin/open"
  task.arguments = [path]
  task.launch()
  exit(0)
}

I found the code here at this link:

enter link description here