HealthKit:与提供的锻炼相关的样本删除问题

时间:2019-05-09 08:55:12

标签: swift health-kit hkhealthstore

使用HealthKit,我正在保存以下数据:

  1. 锻炼
  2. 有功能源
  3. 距离

我正在使用以下代码删除锻炼内容:

self.healthStore?.delete(workout, withCompletion: { (status, error) in

但是上面的代码只是从HealthKit应用程序中删除了锻炼。我想删除锻炼及其相关的样本。我该怎么办?

1 个答案:

答案 0 :(得分:0)

要删除关联的样本,我们需要对特定的HKQuantityTypeIdentifier执行删除查询。

要从锻炼中删除有功能量,请参考以下代码:

 let energyBurnedQuantity = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)

    let predicate = HKQuery.predicateForObjects(from: workout)

    let energyQuery = HKSampleQuery(sampleType: energyBurnedQuantity!, predicate: predicate, limit: 100, sortDescriptors: nil) { (query, result, error) in

        if error == nil {
            guard let resultData = result else {
                return
            }

            if resultData.count > 0 {
                self.healthStore?.delete(resultData, withCompletion: { [unowned self] (status, error) in

                    if status == true {

                        print("Successfully deleted Energy.")
                        })
                    } else {
                        print("Error \(String(describing: error?.localizedDescription))")
                    }
                })
            }
        }
    }

    self.healthStore?.execute(energyQuery)