bdv
bdv

Reputation: 1204

HKSampleQuery returns no results even when there are

I'm trying to get all heart rate samples from the past month, and extract the times and values from them.

So far, I've got the following method:

func getThisMonthsHeartRates() {
    print("func called")
    let heartRateUnit:HKUnit = HKUnit(from: "count/min")
    let heartRateType:HKQuantityType = HKQuantityType.quantityType(forIdentifier: .heartRate)!

    //predicate
    let startDate = Date()
    let endDate = Date() - 1.month
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])

    //descriptor
    let sortDescriptors = [
        NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
    ]

    let heartRateQuery = HKSampleQuery(sampleType: heartRateType,
                                   predicate: predicate,
                                   limit: Int(HKObjectQueryNoLimit),
                                   sortDescriptors: sortDescriptors)
    { (query:HKSampleQuery, results:[HKSample]?, error:Error?) -> Void in

        guard error == nil else { print("error"); return }
        print("results")
        print(results!)

        for result in results! {
            guard let currData:HKQuantitySample = result as? HKQuantitySample else { return }

            print("Heart Rate: \(currData.quantity.doubleValue(for: heartRateUnit))")
            print("quantityType: \(currData.quantityType)")
            print("Start Date: \(currData.startDate)")
            print("End Date: \(currData.endDate)")
            print("Metadata: \(String(describing: currData.metadata))")
            print("UUID: \(currData.uuid)")
            print("Source: \(currData.sourceRevision)")
            print("Device: \(String(describing: currData.device))")
            print("---------------------------------\n")
        }

    }  //eo-query
    healthStore.execute(heartRateQuery)

}//eom

However, the results will always return an empty array, even though I've got samples on my device! Really curious as to how this can be and how to fix it. I'm at a total loss.

Thanks

Update

After logging the query before it gets executed and while it's being executed, this is what the console says:

<HKSampleQuery:0x1c4117610 inactive>

And

<HKSampleQuery:0x1c4117610 deactivated>

I have no idea what this means nor can I find anything online about it.

Upvotes: 5

Views: 1245

Answers (1)

petertoth
petertoth

Reputation: 249

The problem might be that you have requested authorization to write .heartRate sample types, but not to read them as well. In this case you don't receive an error when executing the query, however the samples array will be empty.

I had the same problem because I was requesting authorization this way:

healthStore.requestAuthorization(toShare: types, read: nil) {}

Instead, you need to specify the types that you want to read even though they are already in the types set.

Upvotes: 4

Related Questions