Search code examples
iosswiftmacosapplescript

"Expected end of line but found unknown token." while running AppleScript in swift


I am trying to run applescript code in swift to get information from other applications. Here is a sample code:

var applescript = "tell application "Xcode" \n set fileName to name of window 1 \n end tell"
var error: NSDictionary?
let scriptObject = NSAppleScript(source: applescript)
let output: NSAppleEventDescriptor = scriptObject!.executeAndReturnError(&error)
if (error != nil) {
    print("error: \(String(describing: error))")
}
if output.stringValue == nil{
    let empty = "the result is empty"
    return empty
}
else {
    return (output.stringValue?.description)!
}

But it always return me error messages like this:

error: Optional({
    NSAppleScriptErrorBriefMessage = "Expected end of line but found unknown token.";
    NSAppleScriptErrorMessage = "Expected end of line but found unknown token.";
    NSAppleScriptErrorNumber = "-2741";
    NSAppleScriptErrorRange = "NSRange: {25, 1}";
})

I think the unknown token it mentioned is "\n". Because when I ran other applescripts without "\n" in codes, there was no error message.

Can somebody help me this out? Thank you so much!


Solution

  • You have to escape the inner double quotes

    let applescript = "tell application \"Xcode\" \n set fileName to name of window 1 \n end tell"
    

    Or, more convenient and more legible with the multiline syntax

    let applescript = """
        tell application "Xcode"
            set fileName to name of window 1
        end tell
    """