简体   繁体   中英

Swift + Xcode: use osascript in Mac App

I want to ask if you can use osascript in swift/xcode when designing a Mac (Sierra) app. So I've basically just built an empty app using Xcode and swift.

I would now like to use osascript to launch another app using osascript (preferred).

So I've linked my button to ViewController.swift file.

@IBAction func launchApp(_ sender: NSButton) {
    let path = "/usr/bin/env"
    let arguments = ["osascript -e 'tell app \"iTunes\" to activate'"]
    let task = Process.launchedProcess(launchPath: path, arguments: arguments)
    task.waitUntilExit()
}

But I get this error:

 env: osascript -e 'tell app "iTunes" to activate': No such file or directory

I've also tried using path as /usr/bin/osascript and bash.

Some guidance on this would be great! Thanks :)

Don't use OSAScript on Cocoa level, use NSAppleScript

let script = NSAppleScript(source: "activate application \"iTunes\"")!
var errorDict : NSDictionary?
script.executeAndReturnError(&errorDict)
if errorDict != nil { print(errorDict!) }

If the application is sandboxed you need to add appropriate entitlements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM