Prise en main
Copiez un prompt de configuration incluant les étapes d'installation et le guide markdown complet pour ce plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-health`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/health/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
Installer
Section intitulée « Installation »Vous pouvez utiliser notre configuration assistée par IA pour installer le plugin. Ajoutez les skills Capgo à votre outil d'IA avec la commande suivante :
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsUtilisez ensuite le prompt suivant :
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-health` plugin in my project.Si vous préférez une installation manuelle, installez le plugin en exécutant les commandes suivantes et suivez les instructions spécifiques à chaque plateforme ci-dessous :
bun add @capgo/capacitor-healthbunx cap syncImporter
Section intitulée « Import »import { Health } from '@capgo/capacitor-health';Démarrage rapide
Section intitulée « Démarrage rapide »Vérifiez la disponibilité, demandez l’accès en lecture pour les types nécessaires, puis interrogez une plage de dates.
import { Health } from '@capgo/capacitor-health';
async function loadTodaysSteps() { const { available, reason } = await Health.isAvailable(); if (!available) { console.warn('Health data not available', reason); return; }
await Health.requestAuthorization({ read: ['steps', 'heartRate'], write: ['weight'], });
const today = await Health.readSamples({ dataType: 'steps', startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), endDate: new Date().toISOString(), limit: 500, });
return today;}Exemple : historique Android au-delà de 30 jours
Section intitulée « Exemple : historique Android au-delà de 30 jours »Health Connect limite la lecture des données historiques sauf si l’utilisateur accorde READ_HEALTH_DATA_HISTORY. Activez l’option avec requestHistoryAccess: true et déclarez l’autorisation dans votre manifest Android :
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />await Health.requestAuthorization({ read: ['steps'], requestHistoryAccess: true,});Inspecter historyAccessAvailable et historyAccessAuthorized le résultat pour décider s'il faut afficher un deep link vers les réglages.
Exemple : enregistrer un échantillon de poids
Section intitulée « Exemple : enregistrer un échantillon de poids »await Health.saveSample({ dataType: 'weight', value: 72.4, unit: 'kilogram', startDate: new Date().toISOString(), endDate: new Date().toISOString(),});Exemple : sommeil avec phases
Section intitulée « Exemple : sommeil avec phases »Requête sleep dans read, puis lisez les échantillons pour une fenêtre nocturne. Lorsque la plateforme expose les données de stage, les échantillons peuvent inclure SleepStage segments (deep, rem, light, etc.).
Erreurs courantes
Section intitulée « Erreurs courantes »- L’autorisation se fait par type de données: demandez chaque
HealthDataTypeque vous lisez ou écrivez au préalable. - État d’installation d’Android Health Connect: utiliser
isAvailableetopenHealthConnectSettingslorsque le fournisseur est absent ou désactivé. - L'autorisation History est exclusive à Android: ignoré sur iOS, qui n’applique pas la limite de 30 jours.
- Vérifier avant le prompt: utiliser
checkAuthorizationpour afficher l’interface avant d’appelerrequestAuthorizationà nouveau.
Aperçu de API
Section intitulée « Aperçu API »isAvailable
Section intitulée « isAvailable »Indique si la plateforme actuelle prend en charge le SDK de santé natif.
import { Health } from '@capgo/capacitor-health';
const result = await Health.isAvailable();console.log(result);requestAuthorization
Section intitulée « requestAuthorization »Demande l'accès en lecture/écriture aux types de données fournis.
import { Health } from '@capgo/capacitor-health';
const result = await Health.requestAuthorization({ read: ['steps'] });console.log(result);checkAuthorization
Section intitulée « checkAuthorization »Vérifie le statut d'autorisation pour les types de données fournis sans solliciter l'utilisateur.
import { Health } from '@capgo/capacitor-health';
const result = await Health.checkAuthorization({ read: ['steps'] });console.log(result);readSamples
Section intitulée « readSamples »Lit les échantillons du type de données donné sur la période spécifiée.
import { Health } from '@capgo/capacitor-health';
const result = await Health.readSamples({ dataType: 'steps' });console.log(result);saveSample
Section intitulée « saveSample »Écrit un échantillon unique dans le store de santé natif.
import { Health } from '@capgo/capacitor-health';
await Health.saveSample({ dataType: 'steps', value: 1,});openHealthConnectSettings
Section intitulée « openHealthConnectSettings »Ouvre l’écran des paramètres de Health Connect (Android uniquement). Sur iOS, cette méthode ne fait rien.
Utilisez ceci pour rediriger les utilisateurs vers la gestion de leurs autorisations Health Connect ou pour installer Health Connect s’il n’est pas disponible.
import { Health } from '@capgo/capacitor-health';
await Health.openHealthConnectSettings();showPrivacyPolicy
Section intitulée « showPrivacyPolicy »Affiche la politique de confidentialité de l'application pour Health Connect (Android uniquement). Sur iOS, cette méthode ne fait rien.
Cela affiche le même écran de politique de confidentialité que Health Connect lorsque l’utilisateur appuie sur « Politique de confidentialité » dans la boîte de dialogue d’autorisations.
L'URL de la politique de confidentialité peut être configurée en ajoutant une ressource de type chaîne nommée « health_connect_privacy_policy_url » dans le fichier strings.xml de votre application, ou en plaçant un fichier HTML à l'emplacement www/privacypolicy.html dans vos assets.
import { Health } from '@capgo/capacitor-health';
await Health.showPrivacyPolicy();queryWorkouts
Section intitulée « queryWorkouts »Interroge les sessions d'entraînement depuis le store santé natif. Pris en charge sur iOS (HealthKit) et Android (Health Connect).
import { Health } from '@capgo/capacitor-health';
const result = await Health.queryWorkouts({ workoutType: 'americanFootball' });console.log(result);queryAggregated
Section intitulée « queryAggregated »Interroge les données de santé agrégées depuis le store natif de santé. Agrège les données dans des intervalles de temps (heure, jour, semaine, mois) avec des opérations telles que somme, moyenne, min ou max. C'est plus efficace que de récupérer des échantillons individuels pour de grandes plages de dates.
Pris en charge sur iOS (HealthKit) et Android (Health Connect).
import { Health } from '@capgo/capacitor-health';
const result = await Health.queryAggregated({ dataType: 'steps' });console.log(result);Référence de type
Section intitulée « Référence de type »AvailabilityResult
Section intitulée « AvailabilityResult »export interface AvailabilityResult { available: boolean; /** Platform specific details (for debugging/diagnostics). */ platform?: 'ios' | 'android' | 'web'; reason?: string;}AuthorizationOptions
Section intitulée « AuthorizationOptions »export interface AuthorizationOptions { /** Data types that should be readable after authorization. */ read?: HealthDataType[]; /** Data types that should be writable after authorization. */ write?: HealthDataType[]; /** * Android only: request access to health data older than 30 days. * Requires `android.permission.health.READ_HEALTH_DATA_HISTORY` in the manifest. */ requestHistoryAccess?: boolean;}AuthorizationStatus
Section intitulée « AuthorizationStatus »export interface AuthorizationStatus { readAuthorized: HealthDataType[]; readDenied: HealthDataType[]; writeAuthorized: HealthDataType[]; writeDenied: HealthDataType[];}QueryOptions
Section intitulée « QueryOptions »export interface QueryOptions { /** The type of data to retrieve from the health store. */ dataType: HealthDataType; /** Inclusive ISO 8601 start date (defaults to now - 1 day). */ startDate?: string; /** Exclusive ISO 8601 end date (defaults to now). */ endDate?: string; /** Maximum number of samples to return (defaults to 100). */ limit?: number; /** Return results sorted ascending by start date (defaults to false). */ ascending?: boolean;}ReadSamplesResult
Section intitulée « ReadSamplesResult »export interface ReadSamplesResult { samples: HealthSample[];}WriteSampleOptions
Section intitulée « WriteSampleOptions »export interface WriteSampleOptions { dataType: HealthDataType; value: number; /** * Optional unit override. If omitted, the default unit for the data type is used * (count for `steps`, meter for `distance`, kilocalorie for `calories`, bpm for `heartRate`, kilogram for `weight`). */ unit?: HealthUnit; /** ISO 8601 start date for the sample. Defaults to now. */ startDate?: string; /** ISO 8601 end date for the sample. Defaults to startDate. */ endDate?: string; /** Metadata key-value pairs forwarded to the native APIs where supported. */ metadata?: Record<string, string>; /** For blood pressure data, the systolic value in mmHg. Required when dataType is 'bloodPressure'. */ systolic?: number; /** For blood pressure data, the diastolic value in mmHg. Required when dataType is 'bloodPressure'. */ diastolic?: number;}QueryWorkoutsOptions
Section intitulée « QueryWorkoutsOptions »export interface QueryWorkoutsOptions { /** Optional workout type filter. If omitted, all workout types are returned. */ workoutType?: WorkoutType; /** Inclusive ISO 8601 start date (defaults to now - 1 day). */ startDate?: string; /** Exclusive ISO 8601 end date (defaults to now). */ endDate?: string; /** Maximum number of workouts to return (defaults to 100). */ limit?: number; /** Return results sorted ascending by start date (defaults to false). */ ascending?: boolean; /** * Anchor for pagination. Use the anchor returned from a previous query to continue from that point. * On iOS, this is the ISO 8601 cursor returned by the previous query. On Android, this uses * Health Connect's pageToken. * Omit this parameter to start from the beginning. */ anchor?: string;}QueryWorkoutsResult
Section intitulée « QueryWorkoutsResult »export interface QueryWorkoutsResult { workouts: Workout[]; /** * Anchor for the next page of results. Pass this value as the anchor parameter in the next query * to continue pagination. If undefined or null, there are no more results. */ anchor?: string;}QueryAggregatedOptions
Section intitulée « QueryAggregatedOptions »export interface QueryAggregatedOptions { /** The type of data to aggregate from the health store. */ dataType: HealthDataType; /** Inclusive ISO 8601 start date (defaults to now - 1 day). */ startDate?: string; /** Exclusive ISO 8601 end date (defaults to now). */ endDate?: string; /** Time bucket for aggregation (defaults to 'day'). */ bucket?: BucketType; /** Aggregation operation to perform (defaults to 'sum'). */ aggregation?: AggregationType;}QueryAggregatedResult
Section intitulée « QueryAggregatedResult »export interface QueryAggregatedResult { samples: AggregatedSample[];}HealthDataType
Section intitulée « HealthDataType »export type HealthDataType = | 'steps' | 'distance' | 'calories' | 'heartRate' | 'weight' | 'sleep' | 'respiratoryRate' | 'oxygenSaturation' | 'restingHeartRate' | 'heartRateVariability' | 'bloodPressure' | 'bloodGlucose' | 'bodyTemperature' | 'height' | 'flightsClimbed' | 'exerciseTime' | 'distanceCycling' | 'bodyFat' | 'basalBodyTemperature' | 'basalCalories' | 'totalCalories' | 'mindfulness' | 'workouts';HealthSample
Section intitulée « HealthSample »export interface HealthSample { dataType: HealthDataType; value: number; unit: HealthUnit; startDate: string; endDate: string; sourceName?: string; sourceId?: string; /** Platform-specific unique identifier (HealthKit UUID on iOS, Health Connect metadata ID on Android). */ platformId?: string; /** For sleep data, indicates the sleep state (e.g., 'asleep', 'awake', 'rem', 'deep', 'light'). */ sleepState?: SleepState; /** For blood pressure data, the systolic value in mmHg. */ systolic?: number; /** For blood pressure data, the diastolic value in mmHg. */ diastolic?: number;}Source de vérité
Section intitulée « Source de vérité »Cette page est générée à partir de src/definitions.ts. Relancez la synchronisation lorsque l’API public change en amont.
Continuer depuis Getting Started
Section intitulée « Continuer après Prise en main »Si vous utilisez Prise en main pour planifier les opérations du dashboard et de API, connectez-l’avec Utiliser @capgo/capacitor-health pour la fonctionnalité native dans « Utiliser @capgo/capacitor-health », Aperçu de API pour les détails d'implémentation dans « Vue d'ensemble de API », Introduction pour les détails d'implémentation dans l'introduction, Clés API pour les détails d'implémentation dans « Clés API », et Appareils pour les détails d'implémentation dans Devices.