gpt4 book ai didi

objective-c - 无法在 SWIFT 中解包 NSAppleEventDescriptor

转载 作者:搜寻专家 更新时间:2023-10-31 22:35:38 25 4
gpt4 key购买 nike

我有一个 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")
}

关于objective-c - 无法在 SWIFT 中解包 NSAppleEventDescriptor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29050049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com