[iOS][Obj-C] 今こそ HealthKit を使ってみる

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

こんばんは。ヒヨコマニアの田宮です。

iOS 8 で登場した HealthKit。iOS 9 では色々拡張されているようです。

そんな中、いまひとつ盛り上がりに欠ける HealthKit を今こそ使っていきましょうというのが今回の記事のベースにあります。

テーマ

今回は、歩数を取得してみます。

データ読み込みの許可を得る処理

    HKHealthStore *healthStore = [HKHealthStore new];
    HKQuantityType *type = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    NSSet *types = [NSSet setWithObject:type];    
    [healthStore requestAuthorizationToShareTypes:nil readTypes:types completion:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"Authorization Success!");
            [self showSteps];
        } else {
            NSLog(@"ERROR! %@", error);
        }
    }];

まず、HKHealthStore 型の healthStore を生成します。

次に、今回は、歩数を取得するので、HKQuantityType 型の type として、HKQuantityTypeIdentifierStepCountを指定しています。

最後に、requestAuthorizationToShareTypes:readTypes:completion:で歩数データをアプリ内から取得したい旨、リクエストを投げます。

成功なら Authorization Success! と表示した後、後ほど解説する歩数表示メソッドを呼びます。

失敗の場合、エラーメッセージを出力します。

一定期間内の歩数を取得する処理

主要部分を説明していきます。

クエリを生成する

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *interval = [[NSDateComponents alloc] init];
interval.day = 1;
NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
                                                     fromDate:[NSDate date]];
anchorComponents.hour = 0;
NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];
HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
                                                                           quantitySamplePredicate:nil
                                                                                           options:HKStatisticsOptionCumulativeSum
                                                                                        anchorDate:anchorDate
                                                                                intervalComponents:interval];

この後出てくる、クエリを投げて ヘルスストアから歩数を取得するためのクエリを生成しています。 取得する値の種類を指定している HKQuantityType 型の quantityType では、歩数を表す HKQuantityTypeIdentifierStepCount を指定しています。

クエリを投げる

  query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        }
        NSDate *endDate = [NSDate date];
        NSDate *startDate = [calendar dateByAddingUnit:NSCalendarUnitDay
                                                 value:-2
                                                toDate:endDate
                                               options:0];
        
        [results enumerateStatisticsFromDate:startDate toDate:endDate
                                   withBlock:^(HKStatistics *result, BOOL *stop) {
                                       HKQuantity *quantity = result.sumQuantity;
                                       if (quantity) {
                                           double value = [quantity doubleValueForUnit:[HKUnit countUnit]];
                                           NSLog(@"%f", value);
                                       }
                                   }];
    };
    
  [self.healthStore executeQuery:query];

クエリを投げて、結果を出力する処理です。

NSDate 型の startDatevalue 値では何日前からのデータを取得するかを指定しています。 その後、一日毎に、歩数の合計値を取得・表示しています。

結果

2015-07-08 20:37:41.552 watch_app_exp_04[10242:1364026] authorization success!
2015-07-08 20:37:41.590 watch_app_exp_04[10242:1364093] 1000.000000
2015-07-08 20:37:41.591 watch_app_exp_04[10242:1364093] 250.000000

試験的にヘルスケアアプリ入力したデータが出力されました。 一日毎の歩数の合計値データが表示されています。

まとめ

iOS 9 で拡張される Healthkit。どんどんベンリになります。今こそ活用していきましょう。