kvs-coder / HealthKitReporter

HealthKitReporter. A wrapper for HealthKit framework. Helps to write or read data from Apple Health via HealthKit framework.
https://cocoapods.org/pods/HealthKitReporter
MIT License
70 stars 20 forks source link

Anyone could help me how to delete the sample by HealthKitReporter? #19

Open drainlin opened 1 year ago

drainlin commented 1 year ago

This is my code and I want to delete the sample that I created before. But I got this error such as follows:

Optional(Error Domain=com.apple.healthkit Code=3 "Failed to find some objects for deletion." UserInfo={NSLocalizedDescription=Failed to find some objects for deletion.})

Thank you!

private func deleteSample(){
    do {
        let reporter = try HealthKitReporter()
        let types = [QuantityType.bloodGlucose]
        reporter.manager.requestAuthorization(
            toRead: types,
            toWrite: types
        ) { success, error in
            if success, error == nil {
                reporter.manager.preferredUnits(for: types) { preferredUnits, error in
                    if error == nil {
                        for preferredUnit in preferredUnits {
                            do {
                                let query = try reporter.reader.quantityQuery(
                                    type: try QuantityType.make(from: preferredUnit.identifier),
                                    unit: unit == 1 ? "mmol<180.1558800000541>/L" : "mg/dL"
                                ) { results, error in
                                    if error == nil {

                                        for item in results{
                                            reporter.writer.delete(sample: item ) { success, error in
                                                print(item)
                                                print(success)
                                                print(error)
                                            }
                                        }

                                    } else {
                                        print("error")
                                    }
                                }
                                reporter.manager.executeQuery(query)
                            } catch {
                                print(error)
                            }
                        }
                    } else {
                        print("error")
                    }
                }
            } else {
                print("error")
            }
        }
    } catch {
        print(error)
    }
}