SwiftUI Mac Catalyst how to programmatically close / minimize window

I have my app working fine on iOS and now I am extending to mac with Mac Catalyst. In my workflow, I would like to have a window closed or app quitted after some actions. E.g. A user click on a Save button then my app does some works then minimize window or quit app.

How can I do this? I have looked at scene, scene delegate but don't quite understand how to use it or where I should put it in my code.

Thank you.

Replies

You can close a window by calling requestSceneSessionDestruction(...), passing in the scene session associated with the window.

There is currently no API that can be used to minimize windows.

  • Thank you. I'm novice here.... Could you please give me a sample code of how to implementing this function? I am using SwiftUI and I do not have Scene Delegate. I am not sure where I should put this code.

    Thank you

Add a Comment

Ok. I figured it out. This might be helpful to others.

Step 1 Add this to AppDelegate

class AppDelegate: NSObject, UIApplicationDelegate {
 func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {

            let configuration = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)

            if connectingSceneSession.role == .windowApplication {

                configuration.delegateClass = SceneDelegate.self

            }

            return configuration

        }
}

Step 2 Create SceneDelegate

class SceneDelegate: NSObject, ObservableObject, UIWindowSceneDelegate {

    var window: UIWindow?
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = scene as? UIWindowScene else { return }

        self.window = windowScene.keyWindow

    }

}

Step 3. Then call it like this....

@EnvironmentObject var sceneDelegate: SceneDelegate

.
.
.
.

                    if let myWindow = sceneDelegate.window {

                        print(myWindow.description)

                        guard let scene = myWindow.windowScene else { return }

                        let options = UIWindowSceneDestructionRequestOptions()

                        options.windowDismissalAnimation = .commit

                        UIApplication.shared.requestSceneSessionDestruction(scene.session, options: options, errorHandler: { error in

                            // TODO: - Handle error

                            print("Error")

                        })

                    }