我需要能够从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。。。
所以,我现在要通过查询aHKStatisticsCollectionQuery
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值,但是在枚举结果时,我没有得到任何结果。
我在那个街区有什么地方做错了吗?

最佳答案

通过如下调整代码,可以获得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)
        }
    }
}

10-08 12:15