代码之家  ›  专栏  ›  技术社区  ›  Jack

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

  •  10
  • Jack  · 技术社区  · 7 年前

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

    enter image description here

    通过使用 HealthKit 我正在从Apple Health获取STEPS数据 作为

    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
                            }......
    

    sourcequery提供了多个对象,比如apple watch、my iphone。 HKSampleQuery 它给予 HKQuantitySample 反对。 问题是 [HKQuantitySample] 提供未按日期排序的步骤数据数组。 我正在寻找的数据是俱乐部的日期,如什么苹果健康显示在健康应用程序。

    是的,有一些解决方法,比如手动对数据进行排序 [香港数量样本] 按日期排序。但也可以通过使用 predicates 或者别的什么。请随时询问您是否需要其他信息。

    编辑:@allan建议 我已经加了 HKStatisticsCollectionQuery ,是的,它提供数据 日期 但计数接收的步骤与苹果健康应用程序中的不同。以下代码中是否需要添加/修改内容?

    let last10Day = Calendar.current.date(byAdding: .day, value: -10, to: Date())!
            var interval = DateComponents()
            interval.day = 1
            let quantityType1 = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
            // Create the query
            let query = HKStatisticsCollectionQuery(quantityType: quantityType1,
                                                    quantitySamplePredicate: nil,
                                                    options: .cumulativeSum,
                                                    anchorDate: last10Day,
                                                    intervalComponents: interval)
            // Set the results handler
            query.initialResultsHandler = {
                query, results, error in
    
                guard let statsCollection = results else {
                    // Perform proper error handling here
                    fatalError("*** An error occurred while calculating the statistics: \(String(describing: error?.localizedDescription)) ***")
                }
                let endDate = Date()
                statsCollection.enumerateStatistics(from: last10Day, to: endDate, with: { (statistics, stop) in
                    if let quantity = statistics.sumQuantity() {
                        let date = statistics.startDate
                        let value = quantity.doubleValue(for: HKUnit.count())
                        print("--value-->",value, ",--For Date-->",date)
                    }
                })
            }
                healthStore.execute(query)
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   José    7 年前

    使用 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)
    }
    
        2
  •  1
  •   Allan    7 年前

    如果您希望步骤计数的总和按天分隔,如在运行状况应用程序中,则应使用 HKStatisticsCollectionQuery 不是 HKSampleQuery . 这个 documentation 提供按周分组结果的示例代码,但您可以改为按天分组。