Close other applications using swift - macos

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

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)

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

Related

Pros and cons of splitting Cocoa utility app into helper binary + main app binary?

I'm modernizing and sandboxing an old Cocoa utility and considering approaches. The app lives in the menu bar and works in the background, but shows a Dock icon and a configuration window when the icon is clicked.
There are two approaches:
A. A single binary with LSUIElement=YES, using TransformProcessType to show and hide the dock icon as necessary.
B. A helper tool performs the actual app functionality, manages the menu icon and always runs in LSUIElement mode in background. The main app presents the configuration UI and is only launched when necessary.
The app currently does A. I've noticed that many long-running utility apps have separate helper binaries and basically do B. Examples on my Mac include Paste Helper, TimingHelper, Discord Helper, CCC Helper (for Carbon Copy Cloner), 1Password Extension Helper.
I understand that having a separate helper app is conceptually more pure and potentially allows for better separation of sandbox privileges, but it's also harder to implement, so I doubt that's the sole reason why all these apps opted to have a separate helper binary.
So:
What are the pros and cons of A and B, i.e. why do some choose B over A? Is it required to get some functionality these days?
Is it even possible to have a helper tool outlive the main app in a sandboxed Mac App Store app?
What API does one use to make such a helper? The old-style authorisation APIs seem deprecated, and XPC does not seem like it allows a helper app to launch at startup (and even outliving the main app may be hacky)?
I suspect the reason so many developers choose option B is because this arrangement is now baked into macOS via the "Login Items" facility.
In a nutshell, your main application embeds a second (helper) app and that app is configured as a "Login Item". macOS detects this and automatically adds your helper app to the user's login items. You can control this, programmatically, using SMLoginItemSetEnabled(...).
You end up with a regular app users are familiar with, and a helper app that automatically starts at login and can run in the background. I'm also pretty sure this includes a free XPC connection you can take advantage of.
Read all about it in the Adding Login Items section of the infamous Daemons and Services Programming Guide.
I've never done this myself (I currently install background apps as user agents, which I can do because I don't have a sandboxed app), but I did research it for another project and I know a lot of apps do this.
One disadvantage of option A (based on user feedback from my own apps) is that the main app won't act like a regular app. Using the A approach, your users either can't quit the app (because it will need to automatically restart) or you need a way to hide it in the dock, and then there's no (obvious) way to launch it again. It just gets confusing. If you do let your users quit the app, then the background functionality goes away, and that creates other problems.

OS X: Launching app from dock is a no-op if app is already running headless (via NSApplicationActivationPolicyProhibited)

My app can run with a UI and run headless, chosen via a command-line argument. (I don't want to build two separate apps.) When running headless, I'm calling:
[NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];
during app initialization, and don't show any windows.
This all works fine, and I can run the app headed (via the dock) and headless (via another app passing the command-line argument) at the same time. The little dot shows up next to the dock icon only for the headed app. Good. The problem happens if the headless app is launched first. In that state (no dot in the dock), any clicking on the app icon (or launching via Spotlight or the Finder) does nothing, or sometimes brings up "You can’t open the application “Foo” because it is not responding." Presumably the OS thinks the app is already running headed, and is trying to activate it. Is there a way to convince it to ignore that background app and launch a new instance?
Quitting the background app allows the app to launch normally again from the dock.
I don't want to set LSBackgroundOnly in the plist, because that would require two separate apps unless I changed the setActivationPolicy to NSApplicationActivationPolicyRegular in the case of the headed app. But I've read that doing that causes various other bugs, like the menu bar not always showing up.
Any ideas?
I'm on OS 10.10.5 (the oldest OS I need to support). Thanks for any help!
Update: I just noticed that when clicking on the dock and it appears to do nothing, if there are no app windows open I can see that it actually unhides my app's main window (which was created hidden) but doesn't bring it to the front (presumably it notices that NSApplicationActivationPolicyProhibited is set, though that wasn't enough to prevent it from showing the window!).
Update 2: At this point, I'd settle for a way to notify the user that the reason the app isn't launching is that they need to quit the other app that has sublaunched the headless process. Of course this code would need to be in the headless app, since the headed doesn't even launch.
It looks like you can call setActivationPolicy from applicationShouldHandleReopen and set the policy back to NSApplicationActivationPolicyRegular at that time. I made a test app with the following code and it seems to behave as you describe you would like it to above (although I've only run it on 10.11.5):
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
if NSUserDefaults.standardUserDefaults().stringForKey("background") == "true" {
NSApp.setActivationPolicy(.Prohibited)
print("launched in background")
}
}
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
NSApp.setActivationPolicy(.Regular)
return true
}
}

Mac OS X: interacting with an application programmatically

I am working on a project where I need to call methods on an existing application (my own) and use some of its functionality. For e.g. my application ThunderBolt runs on Mac OS X 10.10. It also provides a dictionary of events that can be called externally through Apple Script or some other way that I don't know yet.
My question is what are the different (and better) ways of interacting with an application programmatically on Mac OSX? If I use something like the following code in Apple Script Editor:
tell application "ThunderBolt"
set open_file to (choose file with prompt "Choose the file you wish to parse")
set theContents to read open_file as data
set retPict to (image convert theContents)
end tell
then it is going to launch ThunderBolt with a splash screen and then call "image convert". This can be done via NSAppleScript but still it would launch the application and call methods/events on it.
Is it possible to somehow create an instance of (or get a pointer to) one of the class inside the application and use that? Something similar to COM or automation on a Windows system?
If you're working on OS X 10.10, you might consider taking a look at JavaScript for Automation (JXA).
With it you can apparently build methods into your app that can be invoked from client scripts written in JS (although I'm not yet familiar with the particulars of how to handle implementation of such a thing on the app side). But many of the apps that ship as part of OS X Yosemite have such APIs built in (e.g. iTunes and Finder).
Here's a great tutorial on JXA written by Alex Guyot: http://www.macstories.net/tutorials/getting-started-with-javascript-for-automation-on-yosemite/
The JXA-Cookbook repo also appears to be a nice resource: https://github.com/dtinth/JXA-Cookbook/wiki
Here's a brief example - this script makes iTunes go back one track. Try it while iTunes is playing (by putting the text into Script Editor, with the language option set to JavaScript, and hitting the Run button):
iTunes = Application('iTunes')
state = iTunes.playerState()
// Console msgs show up in the Messages tab of the bottom view:
console.log("playerState: " + state)
iTunes.backTrack()
Alternatively, you can place the code into a .js file and run it on the command line:
$ osascript itunes-backTrack.js
playerState: playing
The way you specify the 'tell application' is the best way, in my opinion.
What do you do with your app that needs to be called? Maybe some of the functionalities can be done with Applescript? It would simplify things a lot.

Launching app in foreground with Qt under MacOS X

I am having problems with a little Qt 5.0.1 program under Mac OS X 10.8.
(I have not tested any other platforms yet.)
I am launching an external Mac OS X program with this line of code:
QDesktopServices::openUrl(QUrl::fromLocalFile(fullpath));
Where fullpath contains a path to an application like:
/Users/schube/QTWorkspace/HelloWorld-build-Desktop_Qt_5_0_1_clang_64bit-Debug/HelloWorld.app/Contents/MacOS/../../../Aptus.app
(Aptus.app is a random app I've chosen, could be any app. I placed it in this path for testing purposes).
The application starts correctly but always in background; or at least, behind a Finder window. Really strange!
How can I force the new launched app to be sent to the foreground?
Use QProcess instead, but make sure that rather than using the path to the executable as the object to run, pass it to the open command as an argument. Something like this: -
QString cmd = QString("open %1").arg(fullpath); // may need QUrl::fromLocalFile(fullpath)
QProcess::startDetached(cmd);
Without using 'open', it will also open up behind other applications.
Note that you could also use the execute function, if you want to wait for the program to finish.
Also, with the open command, I think you only need to pass the path to the app bundle, rather than full path to its executable in Contents/MacOS. Either should work.
This might be a feature of the Mac OSX's window manager so that it does not steal focus.
You might need to alter your application to minimize.

How to make an Invisible / Hidden Cocoa Application

I want to develop a application like http://orbicule.com/undercover/ or
http://hiddenapp.com/.
I know how I could do that for windows but I have totally no clue, what kind
of approach I would need for mac os x, cocoa/xcode.
Is there anything I should be aware of when building applicatons / background services
with no GUI for mac os x?
The service will post data to the webpage with the usual data like geo location & IP
information about the machine so it should be able to access the internet too.
Please lead me to the right path.
It's fairly straightforward.
Go to:
Information Property List Key Reference
http://developer.apple.com/library/ios/#documentation/general/Reference/InfoPlistKeyReference/Introduction/Introduction.html
in the Launch Services Keys, you will see one called "LSBackgroundOnly" simply define this in your Info.plist and set it to true.
<key>LSBackgroundOnly</key>
<true/>
From the documentation:
LSBackgroundOnly (Boolean - Mac OS X)
specifies whether this application
runs only in the background. If this
key exists and is set to “1”, Launch
Services runs the application in the
background only. You can use this key
to create faceless background
applications. You should also use this
key if your application uses
higher-level frameworks that connect
to the window server, but are not
intended to be visible to users.
Background applications must be
compiled as Mach-O executables. This
option is not available for CFM
applications.
Your application will be a background application.
Give System Startup Programming Topics a read. Create a command line tool project, not a Cocoa Application nor a Cocoa Document-Based application. To provide a GUI to interface with it you'll want to use a separate application (ideally one you don't have to install with the "hidden" app, since you seem not to want it to be easily discoverable).
With the exception of AppKit (UI) stuff, the rest of the basic Cocoa frameworks is still available to you via the command line. This means you'd write the main logic of your app (the non-GUI parts) the same as you would otherwise.

Resources