【问题标题】:How to query healthkit data based upon timestamp in Apple health? [closed]如何根据 Apple Health 中的时间戳查询 healthkit 数据? [关闭]
【发布时间】:2020-12-10 02:45:53
【问题描述】:

在特定时间段内收集activity 信息(例如Calories BurnedExercise time)的最佳方法是什么?

任何方法或提示都是可以理解的。谢谢

【问题讨论】:

    标签: ios swift iphone apple-watch healthkit


    【解决方案1】:

    您可以在 HealthKit 中使用查询类。例如:

    let calendar = NSCalendar.currentCalendar()
     
    let interval = NSDateComponents()
    interval.day = 7
     
    // Set the anchor date to Monday at 3:00 a.m.
    let anchorComponents = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: NSDate())
     
     
    let offset = (7 + anchorComponents.weekday - 2) % 7
    anchorComponents.day -= offset
    anchorComponents.hour = 3
     
    guard let anchorDate = calendar.dateFromComponents(anchorComponents) else {
        fatalError("*** unable to create a valid date from the given components ***")
    }
     
    guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) else {
        fatalError("*** Unable to create a step count type ***")
    }
     
    // Create the query
    let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                            quantitySamplePredicate: nil,
                                            options: .CumulativeSum,
                                            anchorDate: anchorDate,
                                            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: \(error?.localizedDescription) ***")
        }
        
        let endDate = NSDate()
        
        guard let startDate = calendar.dateByAddingUnit(.Month, value: -3, toDate: endDate, options: []) else {
            fatalError("*** Unable to calculate the start date ***")
        }
        
        // Plot the weekly step counts over the past 3 months
        statsCollection.enumerateStatisticsFromDate(startDate, toDate: endDate) { [unowned self] statistics, stop in
            
            if let quantity = statistics.sumQuantity() {
                let date = statistics.startDate
                let value = quantity.doubleValueForUnit(HKUnit.countUnit())
                
                // Call a custom method to plot each data point.
                self.plotWeeklyStepCount(value, forDate: date)
            }
        }
    }
     
    healthStore.executeQuery(query)
    

    您需要根据自己的情况使用这些代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 2018-04-28
      相关资源
      最近更新 更多