当尝试通过以下方式“修改” HKWorkout
时,我一直遇到从HealthKit收到此错误的问题:(1)复制现有锻炼(2)更新元数据(3)删除“旧” ”锻炼(在下面的代码中为selectedWorkout),然后(4)保存修改后的新锻炼。此代码有98%的时间正常工作,但是有2%的时间我会收到此错误,并且最终得到重复的锻炼。我做错什么了吗?
顺便说一句,我真的希望HealthKit让我们修改数据,这样就不必跳舞了。
class func updateMetadataDeleteOldAndSaveNewWorkout(selectedWorkout: HKWorkout, handler: @escaping (Bool,WorkoutManagerError? ) -> Void) {
//configure metadata
// Create a new workout with the old workout's fields and new edited metadata object
let newWorkout = HKWorkout(activityType: selectedWorkout.workoutActivityType, start: selectedWorkout.startDate, end: selectedWorkout.endDate, duration: selectedWorkout.duration, totalEnergyBurned: selectedWorkout.totalEnergyBurned, totalDistance: selectedWorkout.totalDistance, metadata: metadata)
// Delete the old workout
HealthStoreSingleton.sharedInstance.healthStore.delete(selectedWorkout, withCompletion: { (success, error) in
DispatchQueue.main.async {
if let unwrappedError = error {
handler(false, WorkoutManagerError.deleteError(unwrappedError.localizedDescription))
return
}
}
// When delete was successful save the new workout
HealthStoreSingleton.sharedInstance.healthStore.save(newWorkout) { success, error in
DispatchQueue.main.async {
if let unwrappedError = error {
handler(false, WorkoutManagerError.saveError(unwrappedError.localizedDescription))
return
}
if success {
handler(true, nil)
return
} else {
handler(false, WorkoutManagerError.saveError("\(String(describing: error))"))
return
}
}
}
})