如何按小时计算HealthKit Swift的步数

时间:2018-06-04 12:16:29

标签: ios swift health-kit xcode9.3 hkhealthstore

我需要在任何特定日期按小时绘制用户所采取步骤的图表。但如果用户的步骤从今天下午3:58开始到今天下午4:10结束,那么我将在这段时间内获得一个HKStatistics对象。我无法将这些数据分成两个样本,因为我需要在3-4 pm插槽和4-5 pm插槽中采取步骤。

我正在使用此代码。请在需要时更正代码。

   let calendar = Calendar.current

    let interval = NSDateComponents()
    interval.hour = 1

    // Set the anchor date to Monday at 3:00 a.m.
    var anchorComponents = calendar.dateComponents([.day,.hour,.minute], from: Date())

    anchorComponents.day = 0
    anchorComponents.hour = 0
    anchorComponents.minute = 0

    guard let anchorDate = calendar.date(from: anchorComponents) else {
        fatalError("*** unable to create a valid date from the given components ***")
    }

    guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) else {
        fatalError("*** Unable to create a step count type ***")
    }

    // Create the query
    let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                            quantitySamplePredicate: nil,
                                            options: [.cumulativeSum , .separateBySource],
                                            anchorDate: anchorDate,
                                            intervalComponents: interval as DateComponents)

    // 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.date(byAdding: .month, value: -3, to: endDate as Date)else {
            fatalError("*** Unable to calculate the start date ***")
        }

        // Plot the weekly step counts over the past 3 months
        statsCollection.enumerateStatistics(from: startDate, to: endDate as Date) { [unowned self] statistics, stop in

            if let quantity = statistics.sumQuantity() {
                let date = statistics.startDate
                let value = quantity.doubleValue(for: HKUnit.count())
                debugPrint(value)
                debugPrint(date)
                // Call a custom method to plot each data point.
            }
        }
    }

    healthKitManager.healthStore!.execute(query) 

0 个答案:

没有答案