BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

How can I update a @StateObject / @EnvironmentObject from a function?

Forums > SwiftUI

Help - I'm trying to "improve" the structure of my iOS app by splitting it down into multiple source files and have only succeeded in breaking it!

In the top-level app I have an @StateObject and I pass this as a .environmentObject into my ContentView

I have the @EnvironmentObject defined in my ContentView

That part all looks good to me.

I have a .onAppear{myFunction()} on the ContentView body.

The onAppear fires correctly and myFunction() gets called.

myFunction() retrieves a file from a remote website. This also works correctly - I can print() the contents of the file.

So, at this point I have the data I need sitting inside myFunction() but I simply cannot figure how to then update the @StateObject from within myFunction() so that the ContentView gets refreshed via its @EnvironmentObject ...

In summary:

func myFunction() {

fetch file from website <-- works fine

update @StateObject in top-level app with file content <-- cannot get this working

}

Can anyone point me towards a solution?

Many thanks!

   

Well, I have just managed to get it working once again - but I don't know how correct my solution is!

I changed myFunction() to accept the @EnvironmentObject as a parameter from the ContentView .onAppear

Within myFunction() I submit an update to the passed @EnvironmentObject to the .main queue.

This approach seems to correctly update the @StateObject which in turn fires updates to the appropriate views.

   

Have you considered moving myFunction to the state object? So, in .onAppear, you just call to startObject.myFunction() which loads the remote file and updates the published variable in stateObject when it's finished. You dont need topass the state object then as myFunction already has access to self.

Just a thought.

   

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

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.