如何防止我的 macOS 应用程序同时运行多个实例?

问题描述 投票:0回答:2

我有一个应用程序,允许用户使用启动器应用程序通过首选项启用“登录时打开”(请参阅https://en.atjason.com/Cocoa/SwiftCocoa_Auto%20Launch%20at%20Login.html )。但是,当我选中该框以启用它时,启动器应用程序会打开我的应用程序的另一个实例。

xcode macos user-interface xcode9
2个回答
8
投票

我找到了一个可用于此目的的捆绑密钥:

LSMultipleInstancesProhibited
。当设置为
YES
时,无法打开另一个实例。潜在的缺点是它还禁止其他登录用户同时打开该应用程序。

更多详细信息请参见此处: https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html


0
投票

对于 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<<--
}

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.