Fatal error: 'try!' expression unexpectedly raised an error: SwiftData.SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer)

106 views Asked by At

I am using SwiftData in combination with iCloud for a private project to store and synchronize credentials. Since I have different models, I need a common container for UntisConfiguration and ElternportalCredentials.

Since I renamed the model from ElternpotalLoginModel to ElternportalCredentials, the app always crashes on my real iPhone with the following error:

MyApp/ParentPortalCredentialsDataSource.swift:21: Fatal error: 'try!' expression unexpectedly raised an error: SwiftData.SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer)


@Model
final class ElternportalCredentials {

    var mail: String = ""
    var password: String = ""
    
    init(elternportalMail: String = "", elternportalPassword: String = "") {
        self.mail = elternportalMail
        self.password = elternportalPassword
    }
    
}
final class ElternportalCredentialsDataSource {
    private let modelContainer: ModelContainer
    private let modelContext: ModelContext

    @MainActor
    static let shared = ElternportalCredentialsDataSource()

    @MainActor
    private init() {
        let config = ModelConfiguration(groupContainer: .identifier("com.company.myapp"))
        self.modelContainer = try! ModelContainer(for: ElternportalCredentials.self, UntisConfiguration.self, configurations: config)
        self.modelContext = modelContainer.mainContext
    }

    func saveCredentials(credentials: ElternportalCredentials) {
        modelContext.insert(credentials)
        do {
            try modelContext.save()
        } catch {
            fatalError(error.localizedDescription)
        }
    }

    func fetchCredentials() -> [ElternportalCredentials] {
        do {
            return try modelContext.fetch(FetchDescriptor<ElternportalCredentials>())
        } catch {
            fatalError(error.localizedDescription)
        }
    }

    func removeOldCredentials() {
        let credentials = fetchCredentials()
        
        for credential in credentials {
            modelContext.delete(credential)
        }
    }
}

Strangely, this does not happen when I start the app in a newly created simulator. Unfortunately, I cannot test whether the error also occurs on a new physical device on which no previous version of the app was installed.

1

There are 1 answers

0
MultiMedia On BEST ANSWER

I have managed to solve my issue by doing the following:

  1. Navigate to App Identifiers > MyApp > AppGroups.

  2. Add an App Group as shown below: Add App Group on Apple Developer page

  3. Go to the capabilities in your Xcode project and configure the container. App Group Capabilities

It should look like this:

New App Group

  1. Finally, use the newly created container in your code:
    let config = ModelConfiguration(groupContainer: .identifier("group.com.company.MyApp"))