3

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
mattfred
  • 2,689
  • 1
  • 22
  • 38
  • this might help. http://stackoverflow.com/questions/12919389/how-to-force-kill-another-application-in-cocoa-mac-os-x-10-5 – codester Oct 26 '14 at 19:11

2 Answers2

4

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)

AgentBilly
  • 756
  • 5
  • 20
2

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


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


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

Community
  • 1
  • 1
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135