You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift集成AppleScript返回结果时应用崩溃问题排查

问题分析与解决方案

崩溃根源

当目标应用的窗口数≥1时,你的AppleScript没有返回任何值,此时script.executeAndReturnError(&error)返回的NSAppleEventDescriptor对象的stringValue为nil,而你用!强制解包nil值,直接触发了运行时崩溃。此外,代码未处理AppleScript执行可能出现的异常(比如应用未运行、权限不足等),也会增加意外崩溃的概率。

修复方案

1. 修正AppleScript,确保始终返回值

修改脚本逻辑,让它在任何分支都返回明确值,避免无返回的情况:

set bundleID to "\(appBundleID)"
tell application id bundleID
    set windowsCount to (count of windows)
end tell
if windowsCount < 1 then
    return bundleID
else
    return ""
end if

2. 优化Swift代码,安全解包并处理错误

用可选绑定替代强制解包,同时捕获并处理AppleScript的执行错误:

func checkApp(appBundleID: String) -> String {
    let appleScript = """
    set bundleID to "\(appBundleID)"
    tell application id bundleID
        set windowsCount to (count of windows)
    end tell
    if windowsCount < 1 then
        return bundleID
    else
        return ""
    end if
    """

    var output = ""
    if let script = NSAppleScript(source: appleScript) {
        var errorDict: NSDictionary?
        let result = script.executeAndReturnError(&errorDict)
        
        // 安全获取返回值,避免强制解包崩溃
        if let resultString = result.stringValue {
            output = resultString
        }
        
        // 可选:打印错误信息用于调试
        if let error = errorDict {
            print("AppleScript执行错误: \(error)")
        }
    }
    return output
}

3. 额外优化:处理应用未运行的场景

如果目标应用未启动,AppleScript会抛出错误,可在脚本中提前判断应用状态:

set bundleID to "\(appBundleID)"
if application id bundleID is running then
    tell application id bundleID
        set windowsCount to (count of windows)
    end tell
    if windowsCount < 1 then
        return bundleID
    else
        return ""
    end if
else
    -- 应用未运行时按需求返回,此处示例返回bundleID
    return bundleID
end if

内容的提问来源于stack exchange,提问作者iStuces

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:16:17