Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close other applications using swift

Tags:

macos

swift

Is there a way to close running applications in swift? For instance, if the application I create needs to close safari.

like image 968
mattfred Avatar asked Apr 29 '26 17:04

mattfred


2 Answers

Here's a Swift 5 version for closing running applications without using AppleScript (AppleScript is a perfect way but it isn't the only way), Safari is used as the example in this case:

let runningApplications = NSWorkspace.shared.runningApplications
if let safari = runningApplications.first(where: { (application) in
    return application.bundleIdentifier == "com.apple.Safari" && application.bundleURL == URL(fileURLWithPath: NSWorkspace.shared.fullPath(forApplication: "Safari")!)
}) {
    // option 1
    safari.terminate()
    // option 2
    kill(safari.processIdentifier, SIGTERM)
}

SIGTERM instead of SIGKILL, referencing from here

Of course, make sure you notify the user of this activity since this may cause negative impact on the user-experience (for example, user-generated contents in the targeted application are not saved before terminating)

like image 109
AgentBilly Avatar answered May 01 '26 09:05

AgentBilly


It is certainly possible via an applescript directly IF:

your app is not running sandboxed (note that if you plan to distribute it via the App Store, your app will be sandboxed)
OR
your app has the necessary entitlements to use applescript: com.apple.security.scripting-targets (apple needs to approve that AND you need to know which apps to target. this isn't a blanket permission)

then

  • https://apple.stackexchange.com/questions/60401/how-do-i-create-an-applescript-that-will-quit-an-application-at-a-specific-time
  • Can you execute an Applescript script from a Swift Application

if you aren't going for App Store complicity anyways, you might also use NSTask directly scripts / code snippets:

  • How to force kill another application in cocoa Mac OS X 10.5
  • Can you execute an Applescript script from a Swift Application

short & sweet: technically yes, 'politically' maybe :D

like image 22
Daij-Djan Avatar answered May 01 '26 09:05

Daij-Djan