我有一个applescript给了我一个结果。但我无法将该值解包为字符串以便使用它。
var set: String = "set windowTile to \"\"\n"
var tell: String = "tell application \"System Events\"\n"
var setFrontApp: String = "set frontApp to first application process whose frontmost is true\n"
var setFrontAppName: String = "set frontAppName to name of frontApp\n"
var tellProcces: String = "tell process frontAppName\n"
var tellFirst: String = "tell (1st window whose value of attribute \"AXMain\" is true)\n"
var setWindowTitle: String = "set windowTitle to value of attribute \"AXTitle\"\n"
var endTellFirst: String = "end tell\n"
var endTellProcess: String = "end tell\n"
var endTell: String = "end tell"
var startAtLoginScript: NSAppleScript = NSAppleScript(source: set + tell + setFrontApp + setFrontAppName + tellProcces + tellFirst + setWindowTitle + endTellFirst + endTellProcess + endTell)
var scriptResult:NSAppleEventDescriptor = startAtLoginScript.executeAndReturnError(errorInfo)!
NSLog ("%@", scriptResult)
nslog如下所示:
2015-03-14 15:15:14.001 test[7315:161881]
<NSAppleEventDescriptor:'utxt'("test.swift")>
实际结果是一个字符串“test.swift”。如何展开/分析此结果?
我尝试添加:
var number:Int = 1
let result = scriptResult.descriptorAtIndex(number)
我也尝试过使用
descriptorForKeyword(<#keyword: AEKeyword#>)
方法,但我不知道如何设置aekeyword。 最佳答案
您可以使用if…let
语法同时检查nil
的结果,如果结果有值,则将其展开。descriptorAtIndex
将无法得到您想要的内容,因为描述符不包含utxt
条目–它是一个utxt
条目(您可以通过打印出result.descriptorType
来看到这一点,它将为“utxt”提供四个字符的代码)。因此,stringValue
应该得到纯字符串值,但它是可选的,因此您可以在相同的let
中展开。
如果您只想输出数据,println
将在不使用时间戳等的情况下执行此操作。(实际上,NSLog
还将错误记录到控制台中,您可能不希望这样做)
import Foundation
let script = "\n".join([
"set windowTile to \"\"",
"tell application \"System Events\"",
"set frontApp to first application process whose frontmost is true",
"set frontAppName to name of frontApp",
"tell process frontAppName",
"tell (1st window whose value of attribute \"AXMain\" is true)",
"set windowTitle to value of attribute \"AXTitle\"",
"end tell",
"end tell",
"end tell",
])
var errorInfo: NSDictionary?
if let script = NSAppleScript(source: script),
let result = script.executeAndReturnError(&errorInfo),
let text = result.stringValue {
println(text)
}
else if let error = errorInfo {
println(error)
}
else {
println("Unexpected error while executing script")
}