feat: 集成健康数据功能

- 在项目中引入 react-native-health 库以获取健康数据
- 在 Explore 页面中添加步数和能量消耗的显示
- 实现页面聚焦时自动拉取今日健康数据
- 更新 iOS 权限设置以支持健康数据访问
- 添加健康数据相关的工具函数以简化数据获取
This commit is contained in:
richarjiang
2025-08-12 09:29:34 +08:00
parent 9796c614ed
commit 67972fa92b
7 changed files with 278 additions and 6 deletions

53
utils/health.ts Normal file
View File

@@ -0,0 +1,53 @@
import AppleHealthKit, { HealthKitPermissions } from 'react-native-health';
const PERMISSIONS: HealthKitPermissions = {
permissions: {
read: [
AppleHealthKit.Constants.Permissions.StepCount,
AppleHealthKit.Constants.Permissions.ActiveEnergyBurned,
],
write: [],
},
};
export type TodayHealthData = {
steps: number;
activeEnergyBurned: number; // kilocalories
};
export async function ensureHealthPermissions(): Promise<boolean> {
return new Promise((resolve) => {
AppleHealthKit.initHealthKit(PERMISSIONS, (error) => {
if (error) {
console.warn('HealthKit init failed', error);
resolve(false);
return;
}
console.log('HealthKit init success');
resolve(true);
});
});
}
export async function fetchTodayHealthData(): Promise<TodayHealthData> {
const start = new Date();
start.setHours(0, 0, 0, 0);
const options = { startDate: start.toISOString() } as any;
const steps = await new Promise<number>((resolve) => {
AppleHealthKit.getStepCount(options, (err, res) => {
if (err || !res) return resolve(0);
resolve(res.value || 0);
});
});
const calories = await new Promise<number>((resolve) => {
AppleHealthKit.getActiveEnergyBurned(options, (err, res) => {
if (err || !res) return resolve(0);
// library returns value as number in kilocalories
resolve(res[0].value || 0);
});
});
return { steps, activeEnergyBurned: calories };
}