Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open another Mac app

Tags:

xcode

macos

swift

In my app I would like to open another app that is installed on the User's Mac (such as iPhoto). I am not sure what I should be looking for in the documentation. What is this called and how should I do it? Thank you

like image 905
Tom Coomer Avatar asked Dec 16 '14 12:12

Tom Coomer


People also ask

How do I open a second app on Mac?

Click and hold the full-screen button in the upper-left corner of a window. As you hold the button, the window shrinks and you can drag it to the left or right side of the screen. Release the button, then click a window on the other side of the screen to begin using both windows side by side.


2 Answers

Swift 5 or later

import Cocoa

func openPhotos() -> Bool {
    if let photosApp = FileManager.default.urls(
        for: .applicationDirectory,
        in: .systemDomainMask
    ).first?.appendingPathComponent("Photos.app") {
        return NSWorkspace.shared.open(photosApp)
    }
    return false
}

Usage:

if openPhotos() {
    print(true)
}

Or using launchApplication with the app name parameter in the method:

import Cocoa

func openApp(_ named: String) -> Bool {
    NSWorkspace.shared.launchApplication(named)
}

Usage:

if openApp("Photos") {
    print(true)
}
like image 132
Leo Dabus Avatar answered Oct 08 '22 12:10

Leo Dabus


XCode 11 • MacOS Catalina 10.15 • Swift 5

NSWorkspace.shared.launchApplication is deprecated and starting from the MacOS 10.15 the new function NSWorkspace.shared.openApplication shall be used.


Example - open terminal application by its bundle id

guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal") else { return }

let path = "/bin"
let configuration = NSWorkspace.OpenConfiguration()
configuration.arguments = [path]
NSWorkspace.shared.openApplication(at: url,
                                   configuration: configuration,
                                   completionHandler: nil)

Example - open terminal application by its path

let url = NSURL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app", isDirectory: true) as URL

let path = "/bin"
let configuration = NSWorkspace.OpenConfiguration()
configuration.arguments = [path]
NSWorkspace.shared.openApplication(at: url,
                                   configuration: configuration,
                                   completionHandler: nil)
like image 30
vookimedlo Avatar answered Oct 08 '22 12:10

vookimedlo