2

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")
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • What approach did you go for in the end? I'm facing the exact same issue. – bencallis May 16 '20 at 21:10
  • I have used this approach which fits my needs. But now, I have another issue. I don't know how to go back to the first HostingController from HC3 or HC4 – Raphaël Barthomeuf May 18 '20 at 06:02
  • @bencallis, did you ever find a workable solution for this? I have multiple UIHostingControllers in a navigationcontroller that I want to share data between. – spentag May 26 '21 at 23:27

1 Answers1

3

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)
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690