The Xcode preview does not work if i add a EnviromentObject
property wrapper. Everytime i add one the Canvas doesn't build and i get this error:
Cannot preview in this file - [App Name].app may have crashed
If i replace the EnviromentObject
property wrapper with ObservedObject
and initialize it everything works fine.
Here's my code:
class NetworkManager: ObservableObject {
}
struct ContentView : View {
@EnvironmentObject var networkManager: NetworkManager
var body: some View {
Text("Canvas not working")
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(NetworkManager())
}
}
#endif
Update:
It doesn’t load the preview as well when i am using a binding:
struct ContentView : View {
@EnvironmentObject var networkManager: NetworkManager
@Binding var test123: String
var body: some View {
Text("Canvas not working")
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
@State static var test1 = ""
static var previews: some View {
ContentView(test123: $test1).environmentObject(NetworkManager())
}
}
#endif
I'm assuming based on the code you provided that your SceneDelegate
looks like this:
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()
}
I'm not going to pretend I know exactly what the canvas is doing behind the scenes when it generates a preview, but based on the fact that the error specifically states that the app may have crashed, I'm assuming that it's attempting to launch the entire app when it tries to generate a preview. Maybe it needs to use the SceneDelegate
to launch the preview, maybe it's something else entirely - I can't say for sure.
Regardless, the reason the app is crashing is because you aren't passing an environment object in your SceneDelegate
. Your SceneDelegate
should look like this:
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(NetworkManager()))
self.window = window
window.makeKeyAndVisible()
}