Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a new window in Mac Catalyst

I am porting an iPad app using Mac Catalyst. I am trying to open a View Controller in a new window.

If I were using strictly AppKit I could do something as described in this post. However, since I am using UIKit, there is no showWindow() method available.

This article states that this is possible by adding AppKit in a new bundle in the project (which I did), however it doesn't explain the specifics on how to actually present the new window. It reads...

Another thing you cannot quite do is spawn a new NSWindow with a UIKit view hierarchy. However, your UIKit code has the ability to spawn a new window scene, and your AppKit code has the ability to take the resulting NSWindow it's presented in and hijack it to do whatever you want with it, so in that sense you could spawn UIKit windows for auxiliary palettes and all kinds of other features.

Anyone know how to implement what is explained in this article?

TL;DR: How do I open a UIViewController as a new separate NSWindow with Mac Catalyst?

like image 894
Arturo Reyes Avatar asked Nov 15 '19 17:11

Arturo Reyes


People also ask

Does Mac catalyst run on earlier versions of macOS?

The app doesn’t run on earlier versions of macOS. The app supports many system features of macOS without additional source code changes, including a menu bar, a resizable window, and support for trackpad, mouse, and keyboard input. What is the first thing to do when preparing a project for Mac Catalyst?

What can I do with Mac catalyst?

And app lifecycle APIs make your app even easier to manage when it’s running in the background. Mac Catalyst also supports many frameworks — including Accounts, Contacts, Core Audio, GameKit, MediaPlayer, PassKit, and StoreKit — to extend what your apps can do on Mac. HomeKit support means home automation apps can run alongside the Home app on Mac.

How to open a folder in a new window on Mac?

Method 1: By using Option key and Right click 1 Step #2. Now press the option key and right click on the folder. 2 Step #3. A small screen will pop up. Notice how the “Open in New tab” option changes into “Open in New window.” 3 Step #4. Click on it and you shall have new window for your folder. Click on the “Finder” option from your Mac desktop.

How do I build and run the recipes app on Mac?

With the Xcode project set up to use Mac Catalyst, build and run the Recipes app on your Mac, and take a look at the features the new version supports. Choose Product > Destination > My Mac. Setting the Build destination to My Mac builds a local version of the Recipes app. Choose Product > Build. After Xcode builds the app, it’s time to run it.


Video Answer


2 Answers

With SwiftUI you can do it like this (thanks to Ron Sebro):

1. Activate multiple window support:

2. Request a new Scene:

struct ContentView: View {
    var body: some View {
        VStack {
            // Open window type 1
            Button(action: {
                UIApplication.shared.requestSceneSessionActivation(nil,
                                                                   userActivity: NSUserActivity(activityType: "window1"),
                                                                   options: nil,
                                                                   errorHandler: nil)
            }) {
                Text("Open new window - Type 1")
            }

            // Open window type 2
            Button(action: {
                UIApplication.shared.requestSceneSessionActivation(nil,
                                                                   userActivity: NSUserActivity(activityType: "window2"),
                                                                   options: nil,
                                                                   errorHandler: nil)
            }) {
                Text("Open new window - Type 2")
            }
        }
    }
}

3. Create your new window views:

struct Window1: View {
    var body: some View {
        Text("Window1")
    }
}
struct Window2: View {
    var body: some View {
        Text("Window2")
    }
}

4. Change SceneDelegate.swift:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)

            if connectionOptions.userActivities.first?.activityType == "window1" {
                window.rootViewController = UIHostingController(rootView: Window1())
            } else if connectionOptions.userActivities.first?.activityType == "window2" {
                window.rootViewController = UIHostingController(rootView: Window2())
            } else {
                window.rootViewController = UIHostingController(rootView: ContentView())
            }

            self.window = window
            window.makeKeyAndVisible()
        }
    }
like image 176
Lupurus Avatar answered Sep 19 '22 15:09

Lupurus


EDIT : ADDED INFO ON HOW TO HAVE ADDITIONAL DIFFERENT WINDOWS LIKE PANELS

In order to support multiple windows on the mac, all you need to do is to follow supporting multiple windows on the iPad.

You can find all the information you need in this WWDC session starting minute 22:28, but to sum it up what you need to do is to support the new Scene lifecycle model.

Start by editing your target and checking the support multiple window checkmark

enter image description here

Once you do that, click the configure option which should take you to your info.plist. Make sure you have the proper entry for Application Scene Manifest

enter image description here

Create a new swift file called SceneDelegate.swift and just paste into it the following boilerplate code

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
       guard let _ = (scene as? UIWindowScene) else { return }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}

And you're basically done. Run your app, and hit command + N to create as many new windows as you want.

If you want to create a new window in code you can use this:

@IBAction func newWindow(_ sender: Any) {            
    UIApplication.shared.requestSceneSessionActivation(nil, userActivity: nil, options: nil) { (error) in
        //
    }
}

And now we get to the big mystery of how to create additional windows

The key to this is to create multiple scene types in the app. You can do it in info.plist which I couldn't get to work properly or in the AppDelegate.

Lets change the function to create a new window to:

@IBAction func newWindow(_ sender: Any) {     
    var activity = NSUserActivity(activityType: "panel")
    UIApplication.shared.requestSceneSessionActivation(nil, userActivity: activity, options: nil) { (error) in

    }
}

Create a new storyboard for your new scene, create at least one viewcontroller and make sure to set in as the initalviewcontroller in the storyboard.

Lets add to the appdelegate the following function:

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { 
        if options.userActivities.first?.activityType == "panel" {
            let configuration = UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
            configuration.delegateClass = CustomSceneDelegate.self
            configuration.storyboard = UIStoryboard(name: "CustomScene", bundle: Bundle.main)
            return configuration
        } else {
            let configuration = UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
            configuration.delegateClass = SceneDelegate.self
            configuration.storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
            return configuration
        }
    }

By setting the userActivity when requesting a scene we can know which scene to create and create the configuration for it accordingly. New Window from the menu or CMD+N will still create your default new window, but the new window button will now create the UI from your new storyboard.

And tada:

enter image description here

like image 28
Ron Srebro Avatar answered Sep 18 '22 15:09

Ron Srebro