- 在项目中引入 react-native-health 库以获取健康数据 - 在 Explore 页面中添加步数和能量消耗的显示 - 实现页面聚焦时自动拉取今日健康数据 - 更新 iOS 权限设置以支持健康数据访问 - 添加健康数据相关的工具函数以简化数据获取
53 lines
1.4 KiB
TypeScript
53 lines
1.4 KiB
TypeScript
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 };
|
|
} |