I’m new to Swift UI and I am working on an app that should display a full screen view on macOS that does not allow the user to leave or quit the app while the view is being displayed (later only an authorized user should be able to close it with a password). Here is the code I have so far:
@main
struct FingerprintApp: App {
var body: some Scene {
MenuBarExtra("App", systemImage: "lock.shield") {
AppMenu()
}
Window("Lock", id: "lock") {
LockView().onAppear {
guard let window = NSApplication.shared.windows.first(where: { $0.identifier?.rawValue == "lock" }),
let screen = window.screen ?? NSScreen.main else { return }
window.contentView?.enterFullScreenMode(screen, withOptions: nil)
}
}
}
}
struct LockView: View {
@Environment(.openWindow) private var openWindow
@Environment(.dismissWindow) private var dismissWindow
var body: some View {
VStack {
Image(systemName: "lock.shield")
.resizable()
.aspectRatio(contentMode: .fit)
Button("Close", action: close)
}
.scaledToFit()
}
private func close() {
dismissWindow(id: "lock")
}
}
struct AppMenu: View {
@Environment(.openWindow) private var openWindow
var body: some View {
Button(action: lock, label: { Text("Lock") })
Divider()
Button(action: quit, label: { Text("Quit") })
}
private func lock() {
openWindow(id: "lock")
}
private func quit() {
NSApplication.shared.terminate(self)
}
}
I was hoping that as soon as the view appears, it would go into full screen mode and when the button is clicked, it would close the window. But there are two problems. First, when the view goes into full screen mode, it does not scale:
I had to take a picture because for some reason taking screen shots is not possible in this mode. The second problem is that clicking the button has no effect (it seems like the application is frozen although it is not). Also, I was surprised to see that it is impossible to quit the application or swipe to another desktop once the view appeared. While this is a feature I intended to add later, I don’t understand why it happens here.
I also tried to use window.toggleFullScreen(nil)
instead. While this works well, the problem is that I could not find a way to make the application blocking this way (i.e. stop the user from quitting or going to another desktop).
I’m using macOS 14.5 and Xcode 15.4. It seems like a simple problem but for some reason I have been stuck with this for days. I don’t care if the view or the window goes into full screen mode, as long as the view scales properly and I have some way to prevent the user from quitting the application. Please help!