我有一个应用程序,允许用户使用启动器应用程序通过首选项启用“登录时打开”(请参阅https://en.atjason.com/Cocoa/SwiftCocoa_Auto%20Launch%20at%20Login.html )。但是,当我选中该框以启用它时,启动器应用程序会打开我的应用程序的另一个实例。
我找到了一个可用于此目的的捆绑密钥:
LSMultipleInstancesProhibited
。当设置为 YES
时,无法打开另一个实例。潜在的缺点是它还禁止其他登录用户同时打开该应用程序。
对于 flutter macos 应用程序
将此代码片段放入 AppDelegate.swift
import Cocoa
import FlutterMacOS
import app_links
@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
override func application(
...
}
// -->>START<<--
// To prevent closing of app when last window closes
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return false
}
// Check if application there already an instance open if so close the new one
override func applicationDidFinishLaunching(_ notification: Notification) {
if !isSingleInstance() {
NSApplication.shared.terminate(self)
}
}
// if the application is hidden this will bring the window in front
override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag {
for window in sender.windows {
window.makeKeyAndOrderFront(self)
}
}
return true
}
// check if we already have an instance running
private func isSingleInstance() -> Bool {
let runningApps = NSWorkspace.shared.runningApplications
let currentApp = NSRunningApplication.current
for app in runningApps {
if app.bundleIdentifier == currentApp.bundleIdentifier && app.processIdentifier != currentApp.processIdentifier {
app.activate(options: [.activateAllWindows, .activateIgnoringOtherApps])
return false
}
}
return true
}
// -->>END<<--
}