Create SwiftUI App outside of Xcode Project

Hey,

I'm currently trying to get a SwiftUI-App to working that isn't built using an Xcode project but just using a Swift package.

So basically, I have a package with a single executable target and this target contains the following two files:

// ExampleApp.swift

import SwiftUI

@main
struct ExampleApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
// ContentView.swift

import SwiftUI

struct ContentView: View {
    @State private var text = "Hello, world!"

    var body: some View {
        VStack {
            Text(self.text)
                .padding()
            TextField("Enter text", text: self.$text)
                .padding()
        }
    }
}

When I run this code using swift run, the SwiftUI window pops up, but it seems to not be focusable in any way. It doesn't appear in the dock, it always stays behind other windows and I cannot edit the text in the TextField (interestingly button presses are recognized).
Am I missing something in my package that could make this work? Like an Info.plist file or something?
Or is it just impossible to run a SwiftUI App using such a setup?

I hope, someone can help me. Thanks in advance!

I have this clip saved away from somewhere to make it work:

struct MyApp: App {
    init() {
        // Some stuff to make the app work properly when `swift run`.
        // We are before `NSApplicationMain` here so queue it.
        DispatchQueue.main.async {
            NSApp.setActivationPolicy(.regular)
            NSApp.activate(ignoringOtherApps: true)
            NSApp.windows.first?.makeKeyAndOrderFront(nil)
        }
    }
...

Nice, thank you very much!

I ended up putting it into an AppDelegate class, like this:

import SwiftUI

@main
struct ExampleApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ notification: Notification) {
        NSApp.setActivationPolicy(.regular)
        NSApp.activate(ignoringOtherApps: true)
        NSApp.windows.first?.makeKeyAndOrderFront(nil)
    }
}
2 Likes