Shak Feizi
Shak Feizi

Reputation: 9

HKUnit for HKBloodGlucose in HealthKit with Swift

My name is Shak. I'm an iOS developer. Recently, I started learning HealthKit and after some progress I have a problem which I need some help. Here is my problem:

I've been trying to save blood glucose data to healthKit but I'm getting this error that "Cannot convert value of type 'HKUnit.Type' to expected argument type 'HKUnit'". Here is the code:

let bloodGlucoseQuantity = HKQuantity(unit: HKUnit, doubleValue: Double(bloodGlucose))

func saveBloodGlucoseSample(bloodGlucose: Int, date: Date) {
        guard let bloodGlucoseType = HKQuantityType.quantityType(forIdentifier: .bloodGlucose) else {
            fatalError("Blood glucose type is not longer available in HealthKit")
        }
        let bloodGlucoseQuantity = HKQuantity(unit: HKUnit, doubleValue: Double(bloodGlucose))
        let bloodGlucoseSample = HKQuantitySample(type: bloodGlucoseType, quantity: bloodGlucoseQuantity, start: date, end: date)
        HKStore?.save(bloodGlucoseSample) { success, error in
            if let error = error {
                print("Error saving blood glucose sample: \(error.localizedDescription)")
            } else {

                print("Successfully saved blood glucose sample")
            }
        }
    }

If anyone has any experience with HealthKit and specifically with blood glucose type I'll be grateful if you can help me.

Upvotes: 0

Views: 435

Answers (3)

Tinashe Makuti
Tinashe Makuti

Reputation: 161

HealthKit provides preferredUnits that you can use without explicitly creating an HKUnit.

func preferredUnits(
    for quantityTypes: Set<HKQuantityType>,
    completion: @escaping ([HKQuantityType : HKUnit], Error?) -> Void
)

This is the method signature, you can always then have a set of accepted units in the completion handler, which you can use.

Upvotes: 0

Gaurav Katdare
Gaurav Katdare

Reputation: 36

I have developed the same application in Xamarin.forms. We have to pass the actual HKUnit instance and not the direct class. In xamarin.forms I have passed

HKUnit.CreateMoleUnit(HKMetricPrefix.Milli,HKUnit.MolarMassBloodGlucose).UnitDividedBy(HKUnit.Liter)

you have to convert this code in swift and you are good to go.!

Upvotes: 0

psolanki
psolanki

Reputation: 411

let bloodGlucoseQuantity = HKQuantity(unit: HKUnit, doubleValue: Double(bloodGlucose))

You need to use a proper HKUnit instance and not just pass the class. e.g. pass HKUnit(from: "mg/dL") to unit.

Upvotes: 1

Related Questions