探秘React Native的健康数据之门:rn-apple-healthkit
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import RNAppleHealthKit, {
Permission,
AppleHealthKit,
HealthValue,
HealthUnit,
SortOrder,
} from 'rn-apple-healthkit';
export default function App() {
const [steps, setSteps] = useState(0);
useEffect(() => {
(async () => {
try {
const isAvailable = await RNAppleHealthKit.isAvailableAsync();
if (isAvailable) {
const permission = await RNAppleHealthKit.requestAuthorizationAsync({
read: [Permission.StepCount],
});
if (permission[Permission.StepCount]) {
const startDate = new Date();
const endDate = new Date();
endDate.setDate(startDate.getDate() + 1); // One day of data
const stepCount = await AppleHealthKit.queryAggregationAsync(
Permission.StepCount,
startDate,
endDate,
SortOrder.Descending,
HealthUnit.Count
);
const totalSteps = stepCount.value[0].value;
setSteps(totalSteps);
}
}
} catch (error) {
console.error('The user is not allowed to read data from HealthKit', error);
}
})();
}, []);
return (
<View style={styles.container}>
<Text style={styles.text}>Total Steps: {steps}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 20,
textAlign: 'center',
},
});
这段代码使用了rn-apple-healthkit
库来请求用户授权,查询并显示用户在过去24小时内的步数。代码首先检查HealthKit是否可用,然后请求读取步数的权限,并获取数据。如果用户不允许访问或者发生错误,它会捕获错误并在控制台输出错误信息。这个例子展示了如何在React Native应用中整合HealthKit,并且是学习如何与HealthKit交互的一个很好的起点。
评论已关闭