본문 바로가기

시작하기

GitHub

AI 지원 설정으로 플러그인을 설치할 수 있습니다. 다음 명령어로 AI 도구에 Capgo 스킬을 추가하세요:

터미널 창
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

그다음 아래 prompt를 사용하세요:

Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-health` plugin in my project.

Manual Setup을 선호한다면, 다음 명령어를 실행하여 플러그인을 설치하고 아래의 플랫폼별 지침을 따르세요:

터미널 창
bun add @capgo/capacitor-health
bunx cap sync
import { Health } from '@capgo/capacitor-health';

가용성을 확인하고 필요한 유형에 대한 읽기 권한을 요청한 다음, 날짜 범위를 쿼리하세요.

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

사용자가 권한을 허용하지 않으면 Health Connect는 과거 데이터 읽기를 제한합니다. READ_HEALTH_DATA_HISTORY. 다음을 통해 옵트인하고 requestHistoryAccess: true Android manifest에 권한을 선언하세요:

<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />
await Health.requestAuthorization({
read: ['steps'],
requestHistoryAccess: true,
});

Inspect historyAccessAvailable 및 historyAccessAuthorized 를 검사하세요.

예시: 체중 샘플 로그 기록

“예시: 체중 샘플 로그 기록” 섹션
await Health.saveSample({
dataType: 'weight',
value: 72.4,
unit: 'kilogram',
startDate: new Date().toISOString(),
endDate: new Date().toISOString(),
});

예시: 수면 단계 포함

“예시: 수면 단계 포함” 섹션

요청 sleep 에서 read, 그런 다음 특정 야간 시간대의 샘플을 읽습니다. 플랫폼에서 단계 데이터를 제공하면 샘플에 다음이 포함될 수 있습니다: SleepStage 세그먼트 (deep, rem, light, 등).

  • 권한 부여는 데이터 유형별로 적용됩니다: 모두 요청 HealthDataType 미리 읽거나 쓰는.
  • Android Health Connect 설치 상태: 사용 isAvailable 및 openHealthConnectSettings 프로바이더가 없거나 비활성화된 경우.
  • History 권한은 Android 전용입니다: 30일 제한을 사용하지 않는 iOS에서는 무시됩니다.
  • Prompt 전 확인: 사용 checkAuthorization 호출하기 전에 UI를 렌더링하려면 requestAuthorization 다시.

현재 플랫폼이 네이티브 health SDK를 지원하는지 여부를 반환합니다.

import { Health } from '@capgo/capacitor-health';
const result = await Health.isAvailable();
console.log(result);

지정된 데이터 유형에 대한 읽기/쓰기 권한을 요청합니다.

import { Health } from '@capgo/capacitor-health';
const result = await Health.requestAuthorization({ read: ['steps'] });
console.log(result);

사용자에게 프롬프트를 표시하지 않고 지정된 데이터 유형의 권한 상태를 확인합니다.

import { Health } from '@capgo/capacitor-health';
const result = await Health.checkAuthorization({ read: ['steps'] });
console.log(result);

지정된 시간 범위 내에서 해당 데이터 유형의 샘플을 읽어옵니다.

import { Health } from '@capgo/capacitor-health';
const result = await Health.readSamples({ dataType: 'steps' });
console.log(result);

단일 샘플을 네이티브 health store에 기록합니다.

import { Health } from '@capgo/capacitor-health';
await Health.saveSample({
dataType: 'steps',
value: 1,
});

Health Connect 설정 화면을 엽니다 (Android 전용). iOS에서는 아무 동작도 수행하지 않습니다.

사용자가 Health Connect 권한을 관리하도록 안내하거나, 설치되어 있지 않은 경우 Health Connect를 설치하도록 유도할 때 사용합니다.

import { Health } from '@capgo/capacitor-health';
await Health.openHealthConnectSettings();

Health Connect용 앱 개인정보 처리방침을 보여줍니다 (Android 전용). iOS에서는 아무 동작도 수행하지 않습니다.

사용자가 권한 대화 상자에서 “Privacy policy”를 탭했을 때 Health Connect가 보여주는 것과 동일한 개인정보 처리방침 화면을 표시합니다.

개인정보 처리방침 URL은 앱의 strings.xml에 “health_connect_privacy_policy_url”이라는 이름의 문자열 리소스를 추가하거나, assets 폴더의 www/privacypolicy.html 경로에 HTML 파일을 배치하여 설정할 수 있습니다.

import { Health } from '@capgo/capacitor-health';
await Health.showPrivacyPolicy();

네이티브 헬스 스토어에서 운동 세션 데이터를 조회합니다. iOS (HealthKit) 및 Android (Health Connect)를 지원합니다.

import { Health } from '@capgo/capacitor-health';
const result = await Health.queryWorkouts({ workoutType: 'americanFootball' });
console.log(result);

네이티브 헬스 스토어에서 집계된 건강 데이터를 조회합니다. 데이터를 시간 단위(시간, 일, 주, 월)로 묶고 합계, 평균, 최소값, 최대값 등의 연산을 수행합니다. 긴 기간의 데이터를 개별 샘플로 가져오는 것보다 훨씬 효율적입니다.

iOS (HealthKit) 및 Android (Health Connect)를 지원합니다.

import { Health } from '@capgo/capacitor-health';
const result = await Health.queryAggregated({ dataType: 'steps' });
console.log(result);
export interface AvailabilityResult {
available: boolean;
/** Platform specific details (for debugging/diagnostics). */
platform?: 'ios' | 'android' | 'web';
reason?: string;
}
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;
}
export interface AuthorizationStatus {
readAuthorized: HealthDataType[];
readDenied: HealthDataType[];
writeAuthorized: HealthDataType[];
writeDenied: HealthDataType[];
}
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;
}
export interface ReadSamplesResult {
samples: HealthSample[];
}
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;
}
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;
}
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;
}
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;
}
export interface QueryAggregatedResult {
samples: AggregatedSample[];
}
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';
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;
}

이 페이지는 플러그인의 src/definitions.ts에서 생성되었습니다. public API가 업스트림에서 변경되면 동기화를 다시 실행하세요.

사용 중인 경우 시작하기 대시보드와 API 운영을 계획하려면, 이를 다음 항목과 연결하세요: @capgo/capacitor-health 사용하기 @capgo/capacitor-health를 사용하여 네이티브 기능을 구현할 때, API 개요 API Overview의 구현 상세 내용은 소개 Introduction의 구현 상세 내용은 API 키 API Keys의 구현 세부 사항은, 디바이스 Devices의 구현 세부 사항은.