如何按日期获取Apple健康数据?

时间:2018-05-31 09:06:06

标签: swift health-kit hksamplequery

Apple Health应用程序按日期提供数据,如下图所示。

enter image description here

使用PO_HEADER || ITEM || LINE_NUM 1 X 1 1 Y 2 2 Z 1 2 A 2 3 B 1 4 C 1 我从apple health获取步骤数据 如

HealthKit

sourceQuery提供了Apple手表,My iPhone等多个对象。 进一步我使用for let p1 = HKQuery.predicateForSamples(withStart: fromDate, end: Date(), options: .strictStartDate) let p2 = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: true) let timeSortDesriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)//as in health kit entry let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)! let predicate = HKQuery.predicateForSamples(withStart: fromDate, end: Date(), options: .strictStartDate) let sourceQuery = HKSourceQuery(sampleType: quantityType, samplePredicate: predicate, completionHandler: { query,sources,error in if sources?.count != 0 && sources != nil { let lastIndex = sources!.count - 1 var sourcesArray = Array(sources!) for i in 0..<sourcesArray.count { let sourcePredicate = HKQuery.predicateForObjects(from: sourcesArray[i]) let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [p1, p2,sourcePredicate]) let query = HKSampleQuery(sampleType: quantityType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [timeSortDesriptor], resultsHandler: { query, results, error in guard let samples = results as? [HKQuantitySample] else { return }...... 循环,它给出了HKSampleQuery个对象。 问题是HKQuantitySample给出了未按日期排序的步骤数据数组。 我正在寻找像健康应用程序中的苹果健康展示日期俱乐部的数据。

是的,有一种解决方法,比如按日期手动对来自[HKQuantitySample]的数据进行排序。但是可能有使用[HKQuantitySample]或其他内容的解决方法。如果您需要任何额外信息,请随时询问。

编辑:正如@Allan 所建议的那样 我添加了HKStatisticsCollectionQuery,是的,它提供了数据日期,但步骤计数接收与Apple运行状况应用程序中的步骤不同。是以下代码中需要添加/修改的内容吗?

predicates

2 个答案:

答案 0 :(得分:2)

使用HKStatisticsCollectionQuery从特定时段获取数据。以下示例显示了如何获取过去30天的步骤:

private let healthStore = HKHealthStore()
private let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

func importStepsHistory() {
    let now = Date()
    let startDate = Calendar.current.date(byAdding: .day, value: -30, to: now)!

    var interval = DateComponents()
    interval.day = 1

    var anchorComponents = Calendar.current.dateComponents([.day, .month, .year], from: now)
    anchorComponents.hour = 0
    let anchorDate = Calendar.current.date(from: anchorComponents)!

    let query = HKStatisticsCollectionQuery(quantityType: stepsQuantityType,
                                        quantitySamplePredicate: nil,
                                        options: [.cumulativeSum],
                                        anchorDate: anchorDate,
                                        intervalComponents: interval)
    query.initialResultsHandler = { _, results, error in
        guard let results = results else {
            log.error("Error returned form resultHandler = \(String(describing: error?.localizedDescription))")
            return
    }

        results.enumerateStatistics(from: startDate, to: now) { statistics, _ in
            if let sum = statistics.sumQuantity() {
                let steps = sum.doubleValue(for: HKUnit.count())
                print("Amount of steps: \(steps), date: \(statistics.startDate)")
            }
        }
    }

    healthStore.execute(query)
}

答案 1 :(得分:1)

如果您希望按健康应用中的日期分隔步数的总计,则应使用HKStatisticsCollectionQuery,而不是HKSampleQuerydocumentation提供了按周分组结果的示例代码,但您可以逐日修改它。