I integrated coredata framework in iOS10 (Swift3) app that pulls data from server and display. When the app start for the first time, core data don't have any records. After exchanging some information with server, it starts syncing in background thread. I'm able to see that data is being downloaded from server through web service, parsing and storing in core data. But if I quit and start the app, it's showing all the records.
In my view controller, I'm using "NSFetchedResultsController" to display the records in "TableView". I'm creating fetched results controller as shown below:
fileprivate lazy var inspirationsResults: NSFetchedResultsController<Inspiration> = {
// Create Fetch Request
let fetchRequest: NSFetchRequest<Inspiration> = Inspiration.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: false)]
// Create Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataManager.shared.getContext(), sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
return fetchedResultsController
}()
In the viewDidLoad method, I wrote below code to fetch:
do {
try self.inspirationsResults.performFetch()
} catch {
let fetchError = error as NSError
print("\(fetchError), \(fetchError.userInfo)")
}
I also added delegate methods "controllerWillChangeContent, controllerDidChangeContent & didChangeObject" to handle the update/modifications.
I'm using persistentContainer to save the object:
func addInspirations(_ inspirations:[[String: AnyObject]]) {
persistentContainer.performBackgroundTask({ (bgContext) in
bgContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
for tInspiration in inspirations {
let inspiration = Inspiration(context: bgContext)
inspiration.inspirationID = tInspiration[kInspirationId] as! Int32
inspiration.inspirationName = tInspiration[kInspirationName] as? String
}
if bgContext.hasChanges {
do {
try bgContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
})
}
Am I missing anything?