无法从HealthKit获得合理格式的HRV读数

时间:2017-11-17 16:32:25

标签: ios swift health-kit

我需要能够从HealthKit中读取所有HRV读数,并按创建日期对其值进行排序。

我可以使用SampleQuery从HealthKit读取某个时间间隔内的所有读数,如下所示:

func getHRVSampleQuery() {
    let HRVType = HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)

    let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)

    let startDate = Date() - 7 * 24 * 60 * 60 // start date is a week from now
    //  Set the Predicates & Interval
    let predicate: NSPredicate? = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: HKQueryOptions.strictEndDate)

    let sampleQuery = HKSampleQuery(sampleType: HRVType!, predicate: predicate, limit: 30, sortDescriptors: [sortDescriptor]) { sampleQuery, results, error  in
        if(error == nil) {
            for result in results! {
                print("Startdate")
                print(result.startDate)
                print(result.sampleType)
                print(result)
                // print(result.metadata)
            }
        }
    }
    healthStore.execute(sampleQuery)
}

这会打印90.4091 ms AC994386-6981-496A-9C0C-5F6839664302 "Apple Watch van Bas" (4.0), "Watch3,4" (4.0)"Apple Watch" (2017-11-10 15:58:21 +0000 - 2017-11-10 16:03:32 +0000)

完美!我需要的所有价值观: - )

然而,似乎无法获得90.4091ms ...

所以,我现在正在通过查询HKStatisticsCollectionQuery来解决这个问题。

func getHRV() -> Void {
    //   Define the Step Quantity Type
    let HRVType = HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)

    //   Get the start of the day
    let date = Date() - 31 * 24 * 60 * 60
    let cal = Calendar(identifier: Calendar.Identifier.gregorian)
    let newDate = cal.startOfDay(for: date)

    //  Set the Predicates & Interval
    let startDate = Date() - 7 * 24 * 60 * 60 // start date is a week
    var predicate: NSPredicate? = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: HKQueryOptions.strictEndDate)

    // Define interval
    var interval = DateComponents()
    interval.second = 7

    //  Perform the Query
    let query = HKStatisticsCollectionQuery(quantityType: HRVType!, quantitySamplePredicate: predicate, options: .separateBySource, anchorDate: startDate, intervalComponents:interval)

    query.initialResultsHandler = { query, results, error in

        if error != nil {
            print("Cannot read HRV from HealthKit. Either the user hasn't given permission or permissions are not set.")
            //  Something went Wrong
            return
        }

        print(results?.sources())

        if let myResults = results {
            print("\(results! as HKStatisticsCollection)")
            print("results")
            print(results?.sources())

            let startDate = Date() - 7 * 24 * 60 * 60
            print("startDate")
            print(startDate)
            print("End date")
            print(Date() as Date)
            print(myResults)
            myResults.enumerateStatistics(from: startDate, to: Date() as Date) { statistics, stop in
                if let quantity = statistics.averageQuantity() {
                    print(statistics)
                }
            } //end block
    }

    healthStore.execute(query)
}

这里的问题是结果包含正确的HRV值,但在枚举结果时,我没有得到任何东西。

我在那个街区做错了吗?

1 个答案:

答案 0 :(得分:0)

您可以通过调整以下代码来获取HRV值(以ms为单位):

let sampleQuery = HKSampleQuery(sampleType: HRVType!, predicate: predicate, limit: 30, sortDescriptors: [sortDescriptor]) { sampleQuery, results, error  in
    if(error == nil) {
        for result in results! {
            print("Startdate")
            print(result.startDate)
            print(result.sampleType)
            print(result.quantity.doubleValue(for: HKUnit.secondUnit(with: .milli)))
            print(result)
            // print(result.metadata)
        }
    }
}