"Expected end of line but found unknown token." 而 运行 AppleScript 在 swift
"Expected end of line but found unknown token." while running AppleScript in swift
我正在尝试 运行 swift 中的 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)!
}
但它总是 return 我这样的错误消息:
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时,没有报错。
有人可以帮我解决这个问题吗?非常感谢!
你必须转义内部双引号
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
"""
我正在尝试 运行 swift 中的 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)!
}
但它总是 return 我这样的错误消息:
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时,没有报错。
有人可以帮我解决这个问题吗?非常感谢!
你必须转义内部双引号
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
"""