My app. saves a record to iCloud with CloudKit. I would like to check for errors and set a flag based on success or failure. I return the flag via the function call but that does not work. The return value is false even when the save is a success and there is no error. It's because the saveHistoryRecordToCloud function returns false before the completion handler sets savedToCloud to true. I understand this has to do with the asynchronous network call but I'm very new to this and clearly don't understand how to handle it. How do I set what saveHistoryRecordToCloud returns accurately? Thanks for the help! The code is below.
func saveHistoryRecordToCloud(currentWalk: MyCustomTabBarController.Walk ) -> Bool
{
var savedToCloud = false
let history = CKRecord(recordType: "History")
history.setValue(currentWalk.startTime, forKey: "startTime")
history.setValue(currentWalk.duration, forKey: "duration")
activityIndicator.startAnimating()
publicDatabase.save(history) { (savedRecord, error) in
if error != nil
{
print ("Error saving to iCloud " + error.debugDescription)
} else
{
savedToCloud = true
DispatchQueue.main.async {
self.activityIndicator.stopAnimating
}
print ("Saving History worked!! recordID,recordName = ",savedRecord?.recordID.recordName ?? "" )
}
}
return (savedToCloud)
}
and the call
tbc!.currentWalk.savedToCloud = saveHistoryRecordToCloud(currentWalk: tbc!.currentWalk)
print ("tbc!.currentWalk.savedToCloud ", tbc!.currentWalk.savedToCloud) // always returns false
saveHistoryRecordToCloud, where you "return" a bool "success" and call the closure in thesave(history)()one. - Larme