Heart Rate data on apple Watch

前端 未结 4 620
长发绾君心
长发绾君心 2020-11-28 04:23

Can we access the heart rate directly from the apple watch? I know this is a duplicate question, but no one has asked this in like 5 months. I know you can access it from th

4条回答
  •  情话喂你
    2020-11-28 04:49

    You can get heart rate data by starting a workout and query heart rate data from healthkit.

    1. Ask for premission for reading workout data.

      HKHealthStore *healthStore = [[HKHealthStore alloc] init];
      HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
      HKQuantityType *type2 = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
      HKQuantityType *type3 = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
      
      [healthStore requestAuthorizationToShareTypes:nil readTypes:[NSSet setWithObjects:type, type2, type3, nil] completion:^(BOOL success, NSError * _Nullable error) {
      
      if (success) {
          NSLog(@"health data request success");
      
      }else{
          NSLog(@"error %@", error);
      }
      }];
      
    2. In AppDelegate on iPhone, respond this this request

      -(void)applicationShouldRequestHealthAuthorization:(UIApplication *)application{
      
      [healthStore handleAuthorizationForExtensionWithCompletion:^(BOOL success, NSError * _Nullable error) {
              if (success) {
                  NSLog(@"phone recieved health kit request");
              }
          }];
      }
      
    3. Then implement Healthkit Delegate:

      -(void)workoutSession:(HKWorkoutSession *)workoutSession didFailWithError:(NSError *)error{
      
      NSLog(@"session error %@", error);
      }
      
      -(void)workoutSession:(HKWorkoutSession *)workoutSession didChangeToState:(HKWorkoutSessionState)toState fromState:(HKWorkoutSessionState)fromState date:(NSDate *)date{
      
      dispatch_async(dispatch_get_main_queue(), ^{
          switch (toState) {
              case HKWorkoutSessionStateRunning:
      
                  //When workout state is running, we will excute updateHeartbeat
                  [self updateHeartbeat:date];
                  NSLog(@"started workout");
              break;
      
              default:
              break;
          }
          });
      }
      
    4. Now it's time to write **[self updateHeartbeat:date]**

      -(void)updateHeartbeat:(NSDate *)startDate{
      
          //first, create a predicate and set the endDate and option to nil/none 
          NSPredicate *Predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:nil options:HKQueryOptionNone];
      
          //Then we create a sample type which is HKQuantityTypeIdentifierHeartRate
          HKSampleType *object = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
      
          //ok, now, create a HKAnchoredObjectQuery with all the mess that we just created.
          heartQuery = [[HKAnchoredObjectQuery alloc] initWithType:object predicate:Predicate anchor:0 limit:0 resultsHandler:^(HKAnchoredObjectQuery *query, NSArray *sampleObjects, NSArray *deletedObjects, HKQueryAnchor *newAnchor, NSError *error) {
      
          if (!error && sampleObjects.count > 0) {
              HKQuantitySample *sample = (HKQuantitySample *)[sampleObjects objectAtIndex:0];
              HKQuantity *quantity = sample.quantity;
              NSLog(@"%f", [quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]]);
          }else{
              NSLog(@"query %@", error);
          }
      
          }];
      
          //wait, it's not over yet, this is the update handler
          [heartQuery setUpdateHandler:^(HKAnchoredObjectQuery *query, NSArray *SampleArray, NSArray *deletedObjects, HKQueryAnchor *Anchor, NSError *error) {
      
           if (!error && SampleArray.count > 0) {
              HKQuantitySample *sample = (HKQuantitySample *)[SampleArray objectAtIndex:0];
              HKQuantity *quantity = sample.quantity;
              NSLog(@"%f", [quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]]);
           }else{
              NSLog(@"query %@", error);
           }
      }];
      
          //now excute query and wait for the result showing up in the log. Yeah!
          [healthStore executeQuery:heartQuery];
      }
      

    You also have a turn on Healthkit in capbilities. Leave a comment below if you have any questions.

提交回复
热议问题