2016-04-04 36 views
0

私は、iOSデバイスからステップデータを読み込むためにHealthKitを使用しています。ここHealthKitがステップデータを読み取ることができません

は私のコードです:

if ([HKHealthStore isHealthDataAvailable]) { 
     __block double stepsCount = 0.0; 
     self.healthStore = [[HKHealthStore alloc] init]; 
     NSSet *stepsType =[NSSet setWithObject:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]]; 
     [self.healthStore requestAuthorizationToShareTypes:nil readTypes:stepsType completion:^(BOOL success, NSError * _Nullable error) { 
      if (success) { 
       HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; 
       HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:HKObjectQueryNoLimit sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) { 
        if (error != nil) { 
         NSLog(@"results: %lu", (unsigned long)[results count]); 
         for (HKQuantitySample *result in results) { 
          stepsCount += [result.quantity doubleValueForUnit:[HKUnit countUnit]]; 
         } 
         NSLog(@"Steps Count: %f", stepsCount); 
        } else { 
         NSLog(@"error:%@", error); 
       }]; 
       [self.healthStore executeQuery:sampleQuery]; 
       [self.healthStore stopQuery:sampleQuery]; 

       NSLog(@"steps:%f",stepsCount); 
      } 
     }]; 
    } 

私が構築し、手順データを持っているiPhone6上のコードを実行すると設定に - >プライバシー - >健康、アプリがデータを読み取ることが許されていませんしかし、ログ領域のみを示しています

steps:0.000000 

を私はforループにしてNSLog(@"error:%@", error)にブレークポイントを置くが、アプリは中断されません。

誰でも助けることができますか?

+0

エラーパラメータを確認しませんでしたか?あなたは 'results:%lu' logを調べますか?私はそれが 'stopQuery:'どこにあるのかは分かりません。奇妙に思える。 – Larme

+0

@Larme私は 'error'もチェックしましたが、' NSLog(@ "error:%@"、error) 'は何も記録しませんでした。 – CokileCeoi

答えて

1

あなたのコードは実行する前にすぐにクエリを停止します。このクエリでは、終了する前にクエリをキャンセルしない限り、stopQuery:を呼び出す理由はありません。クエリは長寿命ではないため(updateHandlerはありません)、resultsHandlerが呼び出された直後にクエリが停止します。

第2の問題は、コードがステップカウントをあまりにも早く記録しようとしていることです。クエリは非同期で実行され、クエリが完了するとresultsHandlerがバックグラウンドスレッドで呼び出されます。ブロック内にログstepsCountを記録することをお勧めします。

最後に、ユーザーの手順を数えたい場合はHKSampleQueryの結果を合計するのではなく、HKStatisticsQueryとする必要があります。 HKStatisticsQueryは、HealthKitで重複するデータの複数のソースがある場合に、より効率的で正しい結果が得られます。たとえば、iPhoneとApple Watchの両方を持っている場合、現在の実装ではユーザーのステップが2倍にカウントされます。

+0

あなたの答えとアドバイスをいただきありがとうございます!私は 'HKSampleQuery'を' HKStatisticsQuery'に変更しました。これは本当に効率的ですが、健康アプリを開いたときにクエリの結果のみがリアルタイムで更新されるわけではありません。 – CokileCeoi

2

このコードを試してみてください。開始日と終了日を変更するだけです。

-(void) getQuantityResult 
{ 
NSInteger limit = 0; 
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:currentDate endDate:[[NSDate date]dateByAddingTimeInterval:60*60*24*3] options:HKQueryOptionStrictStartDate]; 

NSString *endKey = HKSampleSortIdentifierEndDate; 
NSSortDescriptor *endDate = [NSSortDescriptor sortDescriptorWithKey: endKey ascending: NO]; 

HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount] 
                predicate: predicate 
                 limit: limit 
              sortDescriptors: @[endDate] 
               resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){ 
                dispatch_async(dispatch_get_main_queue(), ^{ 
                 // sends the data using HTTP 
                 int dailyAVG = 0; 
                 for(HKQuantitySample *samples in results) 
                    { 
                  dailyAVG += [[samples quantity] doubleValueForUnit:[HKUnit countUnit]]; 
                 } 
                 lblPrint.text = [NSString stringWithFormat:@"%d",dailyAVG]; 
                 NSLog(@"%@",lblPrint.text); 
                 NSLog(@"%@",@"Done"); 
                }); 
               }]; 
    [self.healthStore executeQuery:query]; 
} 
+0

このコードははるかに簡単で正確なデータを返します。 –

関連する問題