c00000fd
c00000fd

Reputation: 22283

How to execute code before my macOS app starts and prevent it from starting upon some condition using SwiftUI?

My thinking was to achieve that by using willFinishLaunchingWithOptions.

So I created:

import AppKit
import SwiftUI
import Foundation

class AppDelegate: NSObject, NSApplicationDelegate
{
    func application(_ aNotification: Notification,
                             willFinishLaunchingWithOptions launchOptions: [NSApplication : Any]? = nil) -> Bool
    {
        if(!some_check)
        {
             print("Not allowing to start the app")
             return false
        }

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

and then from my app.swift:

import SwiftUI

@main
struct MyApp: App {

    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {

        Window(GlobalConsts.kstrAppTitle, id: "idWndMy")
        {
            ContentView()
        }
    }
}

But my willFinishLaunchingWithOptions is never called.

What am I doing wrong?

Upvotes: 0

Views: 249

Answers (1)

cedricbahirwe
cedricbahirwe

Reputation: 1396

The reason It's not working is because you are using the wrong NSApplicationDelegate protocol method. Try changing your code from:

func application(_ aNotification: Notification,
                 willFinishLaunchingWithOptions launchOptions: [NSApplication : Any]? = nil) -> Bool {
    if(some_check)
    {
        print("Not allowing to start the app")
        return false
    }

    print("Allowing to start")
    return true
}

to the following:

func applicationWillFinishLaunching(_ notification: Notification) {
    print("willFinishLaunchingWithOptions")

    if(some_check) {
        // This will stop your app from starting
        NSApplication.shared.terminate(self)
    }
}

Upvotes: 1

Related Questions