web-dev-qa-db-fra.com

Regardez OS 2.0 beta: accédez au rythme cardiaque

Avec Watch OS 2.0, les développeurs sont censés être autorisés à accéder aux capteurs de rythme cardiaque ... J'adorerais jouer un peu avec et créer un prototype simple pour une idée que j'ai, mais je ne trouve nulle part des informations ou de la documentation sur cette fonctionnalité.

Quelqu'un peut-il m'indiquer comment aborder cette tâche? Tout lien ou information serait apprécié

24
Sr.Richie

Apple n'autorise pas techniquement les développeurs à accéder aux capteurs de fréquence cardiaque dans watchOS 2.0. Ce qu'ils font, c'est fournir un accès direct aux données de fréquence cardiaque enregistrées par le capteur dans HealthKit. Pour ce faire et obtenir des données en temps quasi réel, vous devez effectuer deux tâches principales. Tout d'abord, vous devez indiquer à la montre que vous commencez un entraînement (disons que vous courez):

// Create a new workout session
self.workoutSession = HKWorkoutSession(activityType: .Running, locationType: .Indoor)
self.workoutSession!.delegate = self;

// Start the workout session
self.healthStore.startWorkoutSession(self.workoutSession!)

Ensuite, vous pouvez démarrer une requête de diffusion en continu à partir de HKHealthKit pour vous donner des mises à jour lorsque HealthKit les reçoit:

// This is the type you want updates on. It can be any health kit type, including heart rate.
let distanceType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)

// Match samples with a start date after the workout start
let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: .None)

let distanceQuery = HKAnchoredObjectQuery(type: distanceType!, predicate: predicate, anchor: 0, limit: 0) { (query, samples, deletedObjects, anchor, error) -> Void in
    // Handle when the query first returns results
    // TODO: do whatever you want with samples (note you are not on the main thread)
}

// This is called each time a new value is entered into HealthKit (samples may be batched together for efficiency)
distanceQuery.updateHandler = { (query, samples, deletedObjects, anchor, error) -> Void in
    // Handle update notifications after the query has initially run
    // TODO: do whatever you want with samples (note you are not on the main thread)
}

// Start the query
self.healthStore.executeQuery(distanceQuery)

Tout cela est décrit en détail dans la démo à la fin de la vidéo Quoi de neuf dans HealthKit - WWDC 2015

32
lehn0058

Vous pouvez obtenir des données de fréquence cardiaque en démarrant un entraînement et en interrogeant les données de fréquence cardiaque de healthkit.

Demandez la prémission pour lire les données d'entraînement.

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

Dans AppDelegate sur iPhone, répondez à cette demande

-(void)applicationShouldRequestHealthAuthorization:(UIApplication *)application{

[healthStore handleAuthorizationForExtensionWithCompletion:^(BOOL success, NSError * _Nullable error) {
    if (success) {
        NSLog(@"phone recieved health kit request");
    }
}];
}

Ensuite, implémentez 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;
}
});
}

Il est maintenant temps d'écrire [self updateHeartbeat: date]

-(void)updateHeartbeat:(NSDate *)startDate{

__weak typeof(self) weakSelf = self;

//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<HKSample *> *sampleObjects, NSArray<HKDeletedObject *> *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<HKSample *> *SampleArray, NSArray<HKDeletedObject *> *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];
}

Vous avez également un tour sur Healthkit dans les capacités. Laissez un commentaire ci-dessous si vous avez des questions.

6
NeilNie

Vous pouvez utiliser HKWorkout , qui fait partie du framework HealthKit.

1
vomako

De nombreux kits logiciels pour iOS sont désormais disponibles pour watchOS, comme HealthKit. Vous pouvez utiliser les fonctions et les classes HealthKit (HK) afin de calculer les calories brûlées, de trouver la fréquence cardiaque, etc. Lisez les documentations des développeurs sur Apple pour en savoir plus sur HealthKit. Vous pouvez les trouver sur developer.Apple.com.

0