How can I send events for Scene.handlesExternalEvents(matching:) to receive?

Viewed 917

Partway through the 2020 Apple platform API betas, the method mentioned in the subject was added. (A similar method was added to AnyView.) Does anyone know where the corresponding API to send the external events in the first place is?

2 Answers

Sample for open new window in macOS using sending of Scene.handlesExternalEvents

@main
struct TestAppApp: App {
    var body: some Scene {
        WindowGroup {
            MainView()
        }
        //subscribe on event of open mainView
        .handlesExternalEvents(matching: Set(arrayLiteral: Wnd.mainView.rawValue))
        
        WindowGroup {
            HelperView()
        }
        //subscribe on event of open helperView
        .handlesExternalEvents(matching: Set(arrayLiteral: Wnd.helperView.rawValue))
    }
}

enum Wnd: String, CaseIterable {
    case mainView   = "MainView"
    case helperView = "OtherView"
    
    func open(){
        if let url = URL(string: "taotao://\(self.rawValue)") {
            print("opening \(self.rawValue)")
            NSWorkspace.shared.open(url)
        }
    }
}

and 2 Windows/Views code:

extension TestAppApp {
    struct MainView: View {
        var body: some View {
            VStack {
                Button("Open Main View") {
                    Wnd.mainView.open()
                }
                
                Button("Open Other View") {
                    Wnd.helperView.open()
                }
            }
            .padding(150)
        }
    }

    struct HelperView: View {
        var body: some View {
            HStack {
                Text("This is ") + Text("Helper View!").bold()
            }
            .padding(150)
        }
    }
}

Info.plist changes also needed :

enter image description here

My understanding is that this modifier which works on WindowGroups or Views is there to indicate that the Scene or View supports NSUserActivity which are sent by Handoff, Spotlight, SiriKit or Universal Links. In your Info.plist you declare activities that your app supports (as String identifiers) and in your App structure you indicate which Scene handles which activity so the frameworks can decide the proper Scene to open. In other words, it is not for sending NSEvents within different objects of your app but rather to let SwiftUI know which View or Scene can handle a user activity that your app advertises.

Related