After scouring Apple's SwiftUI docs, the web and stackoverflow, I can't seem to figure out how to use multiple classes and passing EnviromentObject data between them. All the articles on SwiftUI's EnvironmentObject, ObservableObjects, Bindings show how to pass data from a model to a view, but how about from one model to another. Or am I thinking about this the wrong way altogether.
How can I pass a @Published var from Class A to Class B?
In this simple SwiftUI example app I am trying to pass @Published data from a Settings class to a NetworkManager class. This app has a single ContentView with two form fields for username and password with a button that when pressed will contact an API and display the results.
The below code will crash because the NetworkManager mockService function does not know what "settings" is. I can read the "Settings" observed EnvironmentObject in a View, but how do I get that data in another class? I am guessing there is something to do with Bindings here, but not sure what to do.
SceneDelegate:
...
var settings = Settings()
var networkManager = NetworkManager()
...
let contentView = ContentView()
.environmentObject(settings)
.environmentObject(networkManager)
...
ContentView.swift
class Settings: ObservableObject {
@Published var username: String = ""
@Published var password: String = ""
}
// This function in reality will be rewritten and expanded with multiple networking calls
class NetworkManager: ObservableObject {
@Published var token: String = ""
func mockService() {
token = settings.username + settings.password
}
}
struct ContentView: View {
@EnvironmentObject var settings: Settings
@EnvironmentObject var networkManager: NetworkManager
var body: some View {
VStack {
TextField("Username", text: $settings.username)
TextField("Password", text: $settings.password)
Button("Update"){
self.networkManager.mockService()
}
Divider()
Text("\(networkManager.token)")
}
}
}