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.
I have managed to solve my issue by doing the following:
Navigate to App Identifiers > MyApp > AppGroups.
Add an App Group as shown below:
Go to the capabilities in your Xcode project and configure the container.
It should look like this: