I want to create a utility app for myself for macOS. It shall quit other apps. The following code does not produce errors but it also does not quit the System-Preferences-App:
func quitSettings() {
let appToTerminate = NSWorkspace.shared.runningApplications.first(
where: {$0.bundleIdentifier == "com.apple.systempreferences" }
)
if let appToTerminate {
appToTerminate.terminate()
}
}
Update:
When I run this function in a simple playground it actually works! However, running it in from a SwiftUi App does still not work:
import SwiftUI
import Cocoa
@main
struct QuitApp: App {
init() {
quitSettings()
}
func quitSettings() {
let appToTerminate = NSWorkspace.shared.runningApplications.first(
where: {$0.bundleIdentifier == "com.apple.systempreferences" }
)
if let appToTerminate {
print(appToTerminate.terminate()) // prints false
}
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Does anyone know how that can happen and how to fix it?
As you note in the comments, your app is sandboxed. From the docs:
Sandboxed applications can’t use this method to terminate other applications. This method returns false when called from a sandboxed application.
If you want to be able to terminate other apps, you'll need to remove sandboxing.