Skip to content

Instantly share code, notes, and snippets.

@hoishing
Last active November 26, 2022 13:23
Show Gist options
  • Save hoishing/152aa320d44e4b687a080ed463ad2f1f to your computer and use it in GitHub Desktop.
Save hoishing/152aa320d44e4b687a080ed463ad2f1f to your computer and use it in GitHub Desktop.
Adding Login Items for macOS
func applicationDidFinishLaunching(_ aNotification: Notification) {
let runningApps = NSWorkspace.shared.runningApplications
let isRunning = runningApps.contains {
$0.bundleIdentifier == "your.domain.TestAutoLaunch"
}
if !isRunning {
var path = Bundle.main.bundlePath as NSString
for _ in 1...4 {
path = path.deletingLastPathComponent as NSString
}
NSWorkspace.shared.launchApplication(path as String)
}
}
import Cocoa
import ServiceManagement
class ViewController: NSViewController {
let helperBundleName = "your.domain.AutoLaunchHelper"
@IBOutlet weak var autoLaunchCheckbox: NSButton!
@IBAction func toggleAutoLaunch(_ sender: NSButton) {
let isAuto = sender.state == .on
SMLoginItemSetEnabled(helperBundleName as CFString, isAuto)
}
override func viewDidLoad() {
super.viewDidLoad()
let foundHelper = NSWorkspace.shared.runningApplications.contains {
$0.bundleIdentifier == helperBundleName
}
autoLaunchCheckbox.state = foundHelper ? .on : .off
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment