Home > Blockchain >  SwiftUI Pass EnvironmentObject to a class
SwiftUI Pass EnvironmentObject to a class

Time:01-14

I'm struggling with passing an variable to a class.

I have a class with different settings I store. The data is available and might be changed on different views.

class UserData: ObservableObject {
    @Published var ZipCode = "DK6700"   
}

The class is on my main view initialised as StateObject:

struct ContentView: View {
    @StateObject var SavedData = UserData()

    var body: some View {
        NavigationView {
        ChartView()
        }
        .edgesIgnoringSafeArea(.bottom)
        .environmentObject(SavedData)
    }
}

I call the Struct ChartView() where UserData is initialised as

@EnvironmentObject var SavedData: UserData
@ObservedObject var dataModel = DataModel()

and from the corresponding View, i can access the stored ZipCode. So far so good. The ChartView calls another class, where I download data in JSON format. This works as well, but I need the stored ZIP code in this class, and I can't figure out how to pass it. Currently ZIP is hardcoded in the DataModel, and works, but it should be the stored value instead.

My DataModel():

class DataModel: ObservableObject {
    @EnvironmentObject var SavedData: UserData
    @MainActor @Published var Data: [MyData] = []
    var ZIP:String = "3000"

    @MainActor func reload() async {
        let url = URL(string: "https://MyURL?zip=\(ZIP)")!
        let urlSession = URLSession.shared

        do {
            ...
        } catch {
            ...
        }
    }   
}

Any suggestions to get the stored ZIP code to my DataModel Class?

CodePudding user response:

How about changing your function signature to

@MainActor func reload(for zipCode: String) async {

and passing it in when you call the function?

  • Related