HealthKit Swift获得今天的步骤

owl*_*ipe 21 ios swift healthkit

我正在制作一个快速的iOS应用程序,它集成了Health应用程序报告的用户步数.我可以在最后一小时轻松找到用户的步数,使用它作为我的谓词:

let anHourBeforeNow: NSDate = NSDate().dateByAddingTimeInterval(-60 * 60)
let predicate = HKQuery.predicateForSamplesWithStartDate(anHourBeforeNow, endDate: NSDate(), options: .None)
Run Code Online (Sandbox Code Playgroud)

我休息了,所以我可以成功访问用户在最后一小时的步数.但是,如何从一天开始就访问用户的步骤数据,例如步骤部分中显示的Health应用程序?

我想做这样的事情:

let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None)
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有针对时区进行调整(所以它给了我UTC当天的开始,而不是用户所在的那天的开始),而且我也得到了高度膨胀的步数(原因未知).

那么如何获得当天用户的步数,使用与Health中报告的步骤相同的步数,如下图所示:在此输入图像描述

Jos*_*osé 24

当您想要在一段时间内检索数据时,HKStatisticsCollectionQuery更适合使用.使用HKStatisticsQuery来获取特定日期的步骤.

Swift 4.2:

    let healthStore = HKHealthStore()

    func getTodaysSteps(completion: @escaping (Double) -> Void) {
        let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
            guard let result = result, let sum = result.sumQuantity() else {
                completion(0.0)
                return
            }
            completion(sum.doubleValue(for: HKUnit.count()))
        }

        healthStore.execute(query)
    }
Run Code Online (Sandbox Code Playgroud)

  • 该解决方案比公认的解决方案更简单、更有效。 (2认同)

Gug*_*thu 23

以下是使用HKStatisticsCollectionQuery的正确方法,由上面的代码指示.

这是用Swift 3编写的,因此如果不是3,你可能需要将一些代码转换回2.3或2.

斯威夫特3

 func retrieveStepCount(completion: (stepRetrieved: Double) -> Void) {

        //   Define the Step Quantity Type
        let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)

        //   Get the start of the day         
        let date = Date()
        let cal = Calendar(identifier: Calendar.Identifier.gregorian)
        let newDate = cal.startOfDay(for: date)

        //  Set the Predicates & Interval
        let predicate = HKQuery.predicateForSamples(withStart: newDate, end: Date(), options: .strictStartDate)
        var interval = DateComponents()
        interval.day = 1

        //  Perform the Query
        let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: newDate as Date, intervalComponents:interval)

        query.initialResultsHandler = { query, results, error in

            if error != nil {

                //  Something went Wrong
                return
            }

            if let myResults = results{
                myResults.enumerateStatistics(from: self.yesterday, to: self.today) {
                    statistics, stop in

                    if let quantity = statistics.sumQuantity() {

                        let steps = quantity.doubleValue(for: HKUnit.count())

                        print("Steps = \(steps)")
                        completion(stepRetrieved: steps)

                    }
                }
            }


        }

        storage.execute(query)
    }
Run Code Online (Sandbox Code Playgroud)

Objective-C的

HKQuantityType *type = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

NSDate *today = [NSDate date];
NSDate *startOfDay = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] startOfDayForDate:today];

NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startOfDay endDate:today options:HKQueryOptionStrictStartDate];
NSDateComponents *interval = [[NSDateComponents alloc] init];
interval.day = 1;

HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:type quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum anchorDate:startOfDay intervalComponents:interval];

query.initialResultsHandler = ^(HKStatisticsCollectionQuery * _Nonnull query, HKStatisticsCollection * _Nullable result, NSError * _Nullable error) {
  if (error != nil) {
    // TODO
  } else {
    [result enumerateStatisticsFromDate:startOfDay toDate:today withBlock:^(HKStatistics * _Nonnull result, BOOL * _Nonnull stop) {
      HKQuantity *quantity = [result sumQuantity];
      double steps = [quantity doubleValueForUnit:[HKUnit countUnit]];
      NSLog(@"Steps : %f", steps);
    }];
  }
};

[self.storage executeQuery:query];
Run Code Online (Sandbox Code Playgroud)

  • self.yesterday 和 self.today 从哪里来? (2认同)

Joh*_*mos 5

您使用的查询从 Healthkit 获取用户记录的所有步骤,而不是执行 Health 应用程序执行的重复步骤的智能过滤。相反,您希望获取健康应用程序在组合来自不同来源的步骤后生成的聚合步骤数据,以获得准确的计数。

为此,您可以使用以下代码:

func recentSteps2(completion: (Double, NSError?) -> () )
{ // this function gives you all of the steps the user has taken since the beginning of the current day.

    checkAuthorization() // checkAuthorization just makes sure user is allowing us to access their health data.
    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting


    let date = NSDate()
    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let newDate = cal.startOfDayForDate(date)
    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today

    // The actual HealthKit Query which will fetch all of the steps and add them up for us.
    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
        var steps: Double = 0

        if results?.count > 0
        {
            for result in results as! [HKQuantitySample]
            {
                steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
            }
        }

        completion(steps, error)
    }

    storage.executeQuery(query)
}
Run Code Online (Sandbox Code Playgroud)

  • 抱歉,这是不正确的。HKSampleQuery 返回每个步骤记录(它不会删除重复项),并且是计算与谓词匹配的样本总和的低效方法。您应该使用 HKStatisticsQuery。 (4认同)

Har*_*kar 5

对于快速 4.2

1) 获取 HealthKit 权限

import HealthKit

func getHealthKitPermission() {

    delay(0.1) {
        guard HKHealthStore.isHealthDataAvailable() else {
            return
        }

        let stepsCount = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!

        self.healthkitStore.requestAuthorization(toShare: [], read: [stepsCount]) { (success, error) in
            if success {
                print("Permission accept.")
            }
            else {
                if error != nil {
                    print(error ?? "")
                }
                print("Permission denied.")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

2)获取特定日期的步数

func getStepsCount(forSpecificDate:Date, completion: @escaping (Double) -> Void) {
        let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
        let (start, end) = self.getWholeDate(date: forSpecificDate)

        let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
            guard let result = result, let sum = result.sumQuantity() else {
                completion(0.0)
                return
            }
            completion(sum.doubleValue(for: HKUnit.count()))
        }

        self.healthKitStore.execute(query)
    }

    func getWholeDate(date : Date) -> (startDate:Date, endDate: Date) {
        var startDate = date
        var length = TimeInterval()
        _ = Calendar.current.dateInterval(of: .day, start: &startDate, interval: &length, for: startDate)
        let endDate:Date = startDate.addingTimeInterval(length)
        return (startDate,endDate)
    }
Run Code Online (Sandbox Code Playgroud)

如何使用

self.getStepsCount(forSpecificDate: Date()) { (steps) in
                if steps == 0.0 {
                    print("steps :: \(steps)")
                }
                else {
                    DispatchQueue.main.async {
                        print("steps :: \(steps)")
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)


onm*_*133 5

如果您想获取一段时间内每天的总步数,请使用HKStatisticsCollectionQuery,Swift 4.2 中的代码

let startDate = Date().addingTimeInterval(-3600 * 24 * 7)
let endDate = Date()

let predicate = HKQuery.predicateForSamples(
  withStart: startDate,
  end: endDate,
  options: [.strictStartDate, .strictEndDate]
)

// interval is 1 day
var interval = DateComponents()
interval.day = 1

// start from midnight
let calendar = Calendar.current
let anchorDate = calendar.date(bySettingHour: 12, minute: 0, second: 0, of: Date())

let query = HKStatisticsCollectionQuery(
  quantityType: HKSampleType.quantityType(forIdentifier: .stepCount)!,
  quantitySamplePredicate: predicate,
  options: .cumulativeSum,
  anchorDate: anchorDate!,
  intervalComponents: interval
)

query.initialResultsHandler = { query, results, error in
  guard let results = results else {
    return
  }

  results.enumerateStatistics(
    from: startDate,
    to: endDate,
    with: { (result, stop) in
      let totalStepForADay = result.sumQuantity()?.doubleValue(for: HKUnit.count()) ?? 0
    }
  )
}

store.execute(query)
Run Code Online (Sandbox Code Playgroud)