【问题标题】:"Expected end of line but found unknown token." while running AppleScript in swift“预计行尾,但发现未知标记。”在快速运行 AppleScript 时
【发布时间】:2022-01-18 21:48:27
【问题描述】:

我正在尝试快速运行 applescript 代码以从其他应用程序获取信息。 这是一个示例代码:

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)!
}

但它总是返回这样的错误消息:

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}";
})

我认为它提到的未知标记是“\n”。因为当我在代码中运行其他没有“\n”的applescript时,没有错误消息。

有人可以帮我解决这个问题吗?非常感谢!

【问题讨论】:

标签: ios swift macos applescript


【解决方案1】:

你必须转义内部的双引号

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

或者,使用多行语法更方便、更易读

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

【讨论】:

  • 非常感谢您提供此解决方案。我还有一个问题,是否有任何方法可以通过替换“\n”将答案中的第一个字符串转换为具有多行语法的第二个字符串?
  • 转帐是什么意思?这两种形式都可以使用并且做同样的事情。
  • 对不起,我的意思是“转换”。比如以编程方式将第一个单行字符串转换为第二个多行语法。
  • 我还是不明白。两者都是字符串 literals.
  • 很抱歉让您感到困惑。我想我在这里犯了一个错误。非常感谢您的解决方案和您的时间!
猜你喜欢
  • 2010-11-14
  • 2013-12-31
  • 1970-01-01
  • 2017-11-20
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多