IOS app crash on Logout

Hi everyone, as the title suggests my app crashes on logout with the error: "“Fatal error: Unexpectedly found nil while unwrapping an Optional value” due to this line of code:
“let realm = try ! Realm(configuration: app.currentUser!.configuration(partitionValue: “user=(app.currentUser!.id)”))” .

So basically because the user has logged out, one of the views that uses realm is receiving the currenUser as nil which is causing the crash. This makes sense however my root view on app startup is this:

var body: some View
{
    if app.currentUser != nil && app.currentUser?.state == .loggedIn
    {

        BaseView()
 
    }
    else if firstTime
    {
        IntroBase(showIntro: $showIntro)
    }
    else
    {
        LoginView(showIntro: $showIntro)

    }
}

What I expected would happen would be that on logout, the root view changes back to the LoginView and nothing should be calling Realm.

I’m not sure how to fix this? has anyone ran into a similar situation? Any guidance will be appreciated.

Working with (especially synced) realms in a SwiftUI app becomes a lot simpler and more robust in Realm-Cocoa 10.6.

From the view you’ve shown, pass the realm configuration to BaseView:

BaseView().environment(\.realmConfiguration, 
    app.currentUser!.configuration(partitionValue: “user=\(app.currentUser!.id)”)

and then from BaseView, you can get a live (updatable) query results and / or the realm:

@ObservedResults(Item.self) var items
@Environment(\.realm) var itemRealm

Thank you so much for your reply Andrew, it was very helpful. I am looking forward to exploring the changes in version 10.6.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.