Search code examples
swiftuiwatchkit

How does SwiftUI pass EnvironmentObjects between HostingController?


I am trying to implement an Apple Watch app in a similar way as this question: Issues implementing navigation from a main controller to page based controllers in WatchOS using SwiftUI

I am trying to pass data between different HostingControllers. My data is stored in an EnvironmentObject with published properties. If I only use one HostingController, it's fine to share data between the different views. But when using a different HostingController, hosting different views (without segues), I can't find the syntax for using my Environment object from HC1 to HC2, the HC3, etc.

I present the HostingController using this piece of code in my SwiftUI views.

NavigationLink(destinationName: "HC2"){
        Text("Go to HC2")

Solution

  • Here is possible approach

    class AppState: ObservableObject {
        static let shared = AppState()      // shared instance
    
        @Published var setting: String = "some"
    }
    
    class HostingController: WKHostingController<AnyView> {
        override var body: AnyView {
            let contentView = ContentView()
                .environmentObject(AppState.shared)     // << inject !!
            return AnyView(contentView)
        }
    }
    
    class HostingController2: WKHostingController<AnyView> {
        override var body: AnyView {
            let contentView = ContentView2()
                .environmentObject(AppState.shared)     // << inject !!
            return AnyView(contentView)
        }
    }