0

Feel free to edit my title for better clarity.

I am starting a new iOS project and am no longer using SceneDelegate/AppDelegate. My problem is I want my ObservableObject to be an Environmental Object for my entire project but am having trouble converting and finding recent examples.

This is how I defined it in my previous iOS 13 project.

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions){

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    //Environmental View
    let observer = GlobalObserver()

    let baseView = SplashScreenView().environment(\.managedObjectContext, context)
       
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: baseView.environmentObject(observer))
        self.window = window
        window.makeKeyAndVisible()
    }
}

Here is my main simplified

@main
struct DefaultApp: App {
  
    
    //Environmental View
    let observer: GlobalObserver
    
   
    init(){
        observer = GlobalObserver()
    }

    var body: some Scene {
        WindowGroup {
            LoginView()
                //.environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}

The project generated a PersistenceController which I presume had to do with local storage. Do I need to somehow pass my observer into the .environment for loginView?

C. Skjerdal
  • 2,750
  • 3
  • 25
  • 50

1 Answers1

1

Yes, it's exactly as you have it in your example code, except that for some reason you commented it all out. So for instance:

class Thing : ObservableObject {
    @Published var name = "Matt"
}

@main
struct SwiftUIApp: App {
    @StateObject var thing = Thing()
    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(thing)
        }
    }
}

Now in any View struct you just say

@EnvironmentObject var thing : Thing

and presto, you're observing from the global instance.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Yeah that code was auto generated on project create, so I commented it out. Didn't realize I was that close to implementing it, thanks alot! – C. Skjerdal Mar 02 '21 at 17:16