Hello:
I have successfully read data from a plist and want to save that data to CoreData. From the code below I am not getting errors but it is not saving the plist data.
Please suggest what I am missing:
func preloadScq() {
print("Call to preload Data Starts Now")
let preloadedDataKey = "didPreloadData"
UserDefaults.standard.removeObject(forKey: preloadedDataKey)
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: preloadedDataKey) == false {
guard let plistUrl = Bundle.main.url(forResource: "SCQ", withExtension:"plist") else {
return
}
let backgroundContext = persistentContainer.newBackgroundContext()
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
backgroundContext.perform {
let scqObjects = NSEntityDescription.insertNewObject(forEntityName: "SCQ", into: backgroundContext)
if let arrayContents = NSArray(contentsOf: plistUrl) as? [String] {
do {
let plistData = try Data(contentsOf: plistUrl)
let scqList = try PropertyListDecoder().decode([Scq].self, from: plistData)
for scqName in scqList {
let scqObject = SCQ(context: backgroundContext)
scqObject.answer = "answer" // the first object in the plist
print ("Answer is \(scqObject)") // This doesn't print anything
}
try backgroundContext.save()
} catch {
print(error)
print ("Your Record is Saved")
}
}
}
//