Description
After refactoring my app to use the new SwiftUI lifecycle I started getting weird crashes in preview. After a bunch of digging I believe this is the cause:
line 124 Mixpanel.swift:
You have to call initialize(token:trackAutomaticEvents:) before calling the main instance, " +
"or define a new main instance if removing the main one
With the old AppDelegate system your entire app must be built/didFinishLaunchingWithOptions will get called on every SwiftUI preview (which is slow!), and this is where I was calling Mixpanel.initialize().
With the new setup/SwiftUI app lifecycle you don't even have an app delegate, it's SwiftUI from top to bottom like so:
@main
struct YourApp: App {
var body: some Scene {
WindowGroup {
YourAppsMainView()
}
}
You can then hook into this to get app startup/lifecycle stuff, but the key part is when you try to preview a child view that is way down the view hierarchy like:
struct SomeView: View {
var body: some View {
}
}
It is rendered directly without YourAppsMainView() (and thus, mixpanel initialize) ever happening!
Our app is relatively early in adopting the full SwiftUI lifecycle/hierarchy so it makes sense this wouldn't have been caught yet but this will for sure happen more going forward.
My recommendation for a fix would be to wrap the assert such that it can't trigger in the simulator (which is what SwiftUI runs previews in)
#if !targetEnvironment(simulator)
assert(false, "You have to call initialize(token:trackAutomaticEvents:) before calling the main instance, " +
"or define a new main instance if removing the main one")
#endif