Once I download data from server, I am trying to save data in Core Data. As per Apple documentation I am using parent-child context to perform save operation, as follow:
fileprivate func saveDataInLocalDataBase(_ mList: [Info]?) {
if mList != nil {
let mainContext = self.managedObjectContext
let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateContext.parent = mainContext
privateContext.perform {
for mObj in mList! {
let entity = NSEntityDescription.entity(forEntityName: entityName, in:privateContext)
let managedObj = NSManagedObject(entity: entity!, insertInto:privateContext) as! NSManagedObject
mObj.populateFieldsForManagedObject(managedObj)
}
do {
try privateContext.save()
mainContext?.performAndWait {
do {
try mainContext?.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
}
However, sometimes when I try to fetch data from core data it returns 0 objects. That means my data is not saving in Core Data. Can anyone know what is the problem, even though my service returns proper data.
Note: This issue occurs randomly.
Is it possible that when app tries to save data in background and user minimizes the app, so private context it unable to save data when app is in background?
Thanks in advance.