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

从main()手动启动SwiftUI应用时进程脱离引发功能异常的问题求助

从main()手动启动SwiftUI应用时进程脱离引发功能异常的问题求助

我给我的应用做了个双模式启动配置——通过运行时读取环境变量LAUNCH_MODE,可以切换GUI(SwiftUI)或者CLI模式运行。表面上看两种模式都能启动,但GUI模式出了个棘手的问题:SwiftUI窗口好像没和父进程绑定,父进程直接就终止了,导致SwiftUI窗口变成“孤儿状态”,尤其是异步相关的功能根本没法正常工作。

网上几乎找不到从自定义main()里显式调用SwiftUI应用的示例,这段代码基本是我自己摸索着写的,实在搞不清问题出在哪,有没有大佬能指点一下?

下面是我的代码:

@main
struct CourierApp {
    static func main() async throws {
        guard let launchMode = ProcessInfo.processInfo.environment["LAUNCH_MODE"], launchMode == "GUI" else {
            try await launchCLI()
            return
        }
        try await launchGUI()
    }

    private static func launchCLI() async throws {
        guard var courierCLI = try? CourierCLI.parse(ProcessInfo.processInfo.arguments) else {
            throw ValidationError("Invalid arguments. You should invoke Courier providing first your archive and then the output directory for the program. Optionally, some flags can be provided - see the manual for details.")
        }
        try await courierCLI.run()
    }

    private static func launchGUI() async throws {
        await CourierGUI.main()
    }
}

struct CourierCLI: AsyncParsableCommand {
    @Argument var archivePath: String
    @Argument var outputPath: String
    @Flag var uploadToAppStoreConnect = false
    @Option(name: [.customShort("e"), .customLong("entitlements")]) var overrideEntitlements: String? = nil

    mutating func run() async throws {
    }

    func validate() throws {
        if let overrideEntitlements {
            let arrayEntitlements = overrideEntitlements.split(separator: ",")
            guard arrayEntitlements.count <= 2 else {
                throw ValidationError("When passing entitlements to override, you must provide a comma-delimited list of entitlements, taking care to only include entitlements to grant - any omitted will not be granted to the app. Example: 'tracking,bluetooth'.")
            }
        }
    }
}

struct CourierGUI: App {
    var body: some Scene {
        WindowGroup {
            MasterView()
                .navigationTitle("Courier")
        }
        .defaultPosition(.center)
    }
}

备注:内容来源于stack exchange,提问作者Jacob King

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 07:02:59