简体   繁体   中英

Using one EnvironmentObject in another SwiftUI

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM