无法在SWIFT中解包NSAppleEventDescriptor

时间:2015-03-14 14:30:06

标签: objective-c swift applescript cocoa-scripting nsappleeventdescriptor

我有一个Applescript给了我一个结果。但我无法将String的值解除扭曲,因此我可以使用它。

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是否热。

2 个答案:

答案 0 :(得分:2)

您可以使用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")
}

答案 1 :(得分:1)

scriptResult.stringValue(),也许吧? (我不太使用Swift。)