4

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")
3
  • What approach did you go for in the end? I'm facing the exact same issue. Commented May 16, 2020 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 Commented May 18, 2020 at 6: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. Commented May 26, 2021 at 23:27

1 Answer 1

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)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Are there any other approaches? Resorting to using global shared data really doesn't seem ideal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.