问题
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:
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
来源:https://stackoverflow.com/questions/61149135/how-to-use-the-macos-app-dock-menu-to-re-open-the-app-that-has-been-closed-by-u