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

SwiftUI macOS应用:启动前执行代码拦截启动及方法未调用问题

问题原因与解决方案

你的willFinishLaunchingWithOptions方法未被调用的核心原因是方法签名完全不符合NSApplicationDelegate协议要求:

  • 协议规定该方法的第一个参数是NSApplication实例,而非Notification
  • launchOptions的字典键类型应为NSApplication.LaunchOptionsKey,不是NSApplication

修正后的AppDelegate代码

import AppKit
import SwiftUI
import Foundation

class AppDelegate: NSObject, NSApplicationDelegate {
    func application(_ application: NSApplication, willFinishLaunchingWithOptions launchOptions: [NSApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        if !some_check {
            print("Not allowing to start the app")
            // 主动调用终止逻辑,确保应用彻底退出
            NSApplication.shared.terminate(nil)
            return false
        }

        print("Allowing to start")
        return true
    }
}

额外说明

  1. 仅返回false有时无法彻底阻止应用启动,建议搭配NSApplication.shared.terminate(nil)强制终止进程
  2. 确保some_check变量已正确定义并初始化,避免因变量未赋值导致逻辑异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:00:49