1

HKWorkout我在尝试“修改”时遇到了一个长期存在的问题,即通过(1)复制现有锻炼(2)更新元数据(3)删除“旧”锻炼(在我的代码中选择锻炼)从 HealthKit ) 然后 (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 
                            }
                        }
                    }
                })
4

0 回答 0