UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Interaction from API class to view

Forums > SwiftUI

My SwiftUI app has an APIManager class that does all the heavy lifting out to our web services. So for example, my view may go ask the APIManager to authenticate to our servers, or get a list of objects. The API then needs to pass results back to the view.

I've been able to return the data back to the view by way of my errorObject class, and then update my userData. I would much rather update the UserData class directly from APIManager instead of making my errorObject increasingly complex with each additional API call.

class UserData : ObservableObject  {
   @Published var someString: String = ""
}

The thought is to ask the API the questions from the views, let the API update UserData, let the views consume the data. I've tried adding the @EnvironmentObject to APIManager but he's not happy when I try to update.

public class APIManager {

  @EnvironmentObject var userData : UserData

  func testThis(){
    userData.someString="hello from the API"
  }

}

If I call API.testThis() from the view, it tells me: "no observableObject of type userData found"

What am I missing?

2      

@EnvironmentObject (and the other wrappers too) is only available within a View

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.