skip to Main Content

I’m trying to use two different environment variables in my program. One of them, "UserInfo", holds all of the user info for the current authenticated user. The code for this is shown below.

public class UserInfo: ObservableObject {
    some stuff here....
}

The next is a session manager that manages a workout session for the user. However, in this one I want to be able to use the user data from the userInfo environment variable shown above.

class SessionManager: ObservableObject {
    @EnvironmentObject var userInfo: UserInfo
    some other stuff here.....
}

This is where the environment variables are passed in.

@main
struct MyApp: App {
    @StateObject var sessionManager = SessionManager()
    @StateObject var userInfo = UserInfo()
    
    init() {
        FirebaseApp.configure()
    }
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(userInfo)
                .environmentObject(sessionManager)
        }
    }
}

The error I get when I run this is "Fatal error: No ObservableObject of type UserInfo found. A View.environmentObject(_:) for UserInfo may be missing as an ancestor of this view." This comes from the SessionManager.

How can I use the information from userInfo within the SessionManager class?

2

Answers


  1. Usually there is just one environmentObject which would contain the user and session structs.

    Login or Signup to reply.
  2. I think you are trying to do this in the wrong way,

    As per my knowledge, we can only pass the EnvironmentObject from one SwiftUI view to another SwiftUI view, and here you are trying to pass the EnvironmentObject value to the ContentView and your use case is to need UserInfo in the SessionManager, that I think we can not do with the help of EnvironmentObject.

    You can pass the UserInfo in the SessionManager in its initializer and then you will be able to use it there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search