feat: 集成健康数据功能优化
- 在 app.json 中添加 react-native-health 的配置以启用健康 API - 在 Explore 页面中重构健康数据加载逻辑,增加加载状态提示 - 更新健康数据获取函数,增强错误处理和日志输出 - 修改 iOS 权限设置,确保健康数据访问权限的正确配置 - 更新 Info.plist 中的健康数据使用说明
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import AppleHealthKit, { HealthKitPermissions } from 'react-native-health';
|
||||
import type { HealthKitPermissions } from 'react-native-health';
|
||||
import AppleHealthKit from 'react-native-health';
|
||||
|
||||
const PERMISSIONS: HealthKitPermissions = {
|
||||
permissions: {
|
||||
@@ -17,37 +18,66 @@ export type TodayHealthData = {
|
||||
|
||||
export async function ensureHealthPermissions(): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
console.log('开始初始化HealthKit...');
|
||||
|
||||
AppleHealthKit.initHealthKit(PERMISSIONS, (error) => {
|
||||
if (error) {
|
||||
console.warn('HealthKit init failed', error);
|
||||
console.error('HealthKit初始化失败:', error);
|
||||
// 常见错误处理
|
||||
if (typeof error === 'string') {
|
||||
if (error.includes('not available')) {
|
||||
console.warn('HealthKit不可用 - 可能在模拟器上运行或非iOS设备');
|
||||
}
|
||||
}
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
console.log('HealthKit init success');
|
||||
console.log('HealthKit初始化成功');
|
||||
resolve(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchTodayHealthData(): Promise<TodayHealthData> {
|
||||
console.log('开始获取今日健康数据...');
|
||||
|
||||
const start = new Date();
|
||||
start.setHours(0, 0, 0, 0);
|
||||
const options = { startDate: start.toISOString() } as any;
|
||||
|
||||
console.log('查询选项:', options);
|
||||
|
||||
const steps = await new Promise<number>((resolve) => {
|
||||
AppleHealthKit.getStepCount(options, (err, res) => {
|
||||
if (err || !res) return resolve(0);
|
||||
if (err) {
|
||||
console.error('获取步数失败:', err);
|
||||
return resolve(0);
|
||||
}
|
||||
if (!res) {
|
||||
console.warn('步数数据为空');
|
||||
return resolve(0);
|
||||
}
|
||||
console.log('步数数据:', res);
|
||||
resolve(res.value || 0);
|
||||
});
|
||||
});
|
||||
|
||||
const calories = await new Promise<number>((resolve) => {
|
||||
AppleHealthKit.getActiveEnergyBurned(options, (err, res) => {
|
||||
if (err || !res) return resolve(0);
|
||||
if (err) {
|
||||
console.error('获取消耗卡路里失败:', err);
|
||||
return resolve(0);
|
||||
}
|
||||
if (!res || !Array.isArray(res) || res.length === 0) {
|
||||
console.warn('卡路里数据为空或格式错误');
|
||||
return resolve(0);
|
||||
}
|
||||
console.log('卡路里数据:', res);
|
||||
// library returns value as number in kilocalories
|
||||
resolve(res[0].value || 0);
|
||||
resolve(res[0]?.value || 0);
|
||||
});
|
||||
});
|
||||
|
||||
console.log('今日健康数据获取完成:', { steps, calories });
|
||||
return { steps, activeEnergyBurned: calories };
|
||||
}
|
||||
Reference in New Issue
Block a user