HealthKit Swift获得今天的步骤 [英] HealthKit Swift getting today's steps

查看:455
本文介绍了HealthKit Swift获得今天的步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个快速的iOS应用程序,它集成了Health应用程序报告的用户步数。我可以很容易地找到用户在过去一小时内的步数,使用它作为我的谓词:

I am making a swift iOS app that integrates with a user's step count as reported by the Health app. I can easily find the user's step count in the last hour, using this as my predicate:

let anHourBeforeNow: NSDate = NSDate().dateByAddingTimeInterval(-60 * 60)
let predicate = HKQuery.predicateForSamplesWithStartDate(anHourBeforeNow, endDate: NSDate(), options: .None)

我休息了,所以我可以成功访问用户最后一小时的步数。 但是,从一天开始,我怎样才能访问用户的步骤数据,例如步骤部分中显示的健康应用程序?

And I have the rest down, so I can successfully access the user's step count for the last hour. But how can I access the user's step data since the day began, like the Health app displays in the steps section?

我正在尝试做这样的事情:

I am trying to do something like this:

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

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

but this code does not adjust for time zone (so it gives me the beginning of the day in UTC, not the beginning of the day where the user is) and I am also getting highly inflated step counts (for reasons unknown).

那么我如何得到当天用户的步数,数字相同Health中报告的步骤如下图所示:

推荐答案

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

Here is the right way using HKStatisticsCollectionQuery courtesy of the direction from the code above.

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

This is written in Swift 3 so you may have to convert some of the code back to 2.3 or 2 if not on 3 yet.

Swift 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)
    }

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];

这篇关于HealthKit Swift获得今天的步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆