nativeScript-fitness
Google Fit 和 Apple HealthKit。
npm i --save nativescript-fitness

NativeScript 的健身插件

这是一个 NativeScript 插件,用于抽象 Apple HealthKit 和 Google Fit,以从用户的设备读取健康数据。

这是 nativescript-health-data 的分支。

先决条件

Android

Google Fit API 密钥 - 访问 Google 开发者控制台,创建一个项目,并启用 Fitness API。然后在 凭据 下,为 Android 应用创建一个 Fitness API OAuth2 客户端 ID(选择 用户数据 并点击 我需要什么凭据? 按钮)。如果您使用 Linux/maxOS,请使用以下代码生成 SHA1-key。

keytool -exportcert -keystore path-to-debug-or-production-keystore -list -v

注意默认(调试)密钥库密码为空。

iOS

请确保您已启用您的应用 ID 中的 HealthKit 权限。

安装

使用 NativeScript CLI 安装插件

tns plugin add nativescript-fitness

API

以下示例全部为 TypeScript,并且 demo 是在 Nativescript w/ Angular 中开发的。

以下是导入和实例化插件的方法,所有示例都期望这种设置

import { AggregateBy, Fitness, FitnessType } from "nativescript-fitness";

export class MyHealthyClass {
private fitness: Fitness;

constructor() {
this.fitness = new Fitness();
}
}

isAvailable

这会告诉您设备是否支持健康数据。在 iOS 上这可能是始终为 true。在 Android 上,如果 Play Services 版本不够新,用户将(自动)被提示更新。如果您不希望这种行为,请将 false 传递给此函数,如下所示。

this.fitness.isAvailable(false)
.then(available => console.log(available));

isAuthorized

此函数(以及下一个函数)接受一个 ArrayFitnessType

  • name 可以是 '可用的数据类型' 之一。
  • accessType 可以是 readwritereadAndWrite(请注意,此插件目前仅支持读取数据,但将会改变)。

iOS 在这里有点傻:如果您只请求了 'read' 访问,您将永远不会从这个方法中得到 true 响应。详细信息在这里。

this.fitness.isAuthorized([<FitnessType>{name: "steps", accessType: "read"}])
.then(authorized => console.log(authorized));

requestAuthorization

此函数接受与 isAuthorized 相同的参数,并在用户之前未授权您的应用访问传递的任何 FitnessType 时触发同意屏幕。

请注意,此插件目前仅支持读取数据,但将会改变。

const types: Array<FitnessType> = [
{name: "height", accessType: "write"},
{name: "weight", accessType: "readAndWrite"},
{name: "steps", accessType: "read"},
{name: "distance", accessType: "read"}
];

this.fitness.requestAuthorization(types)
.then(authorized => console.log(authorized))
.catch(error => console.log("Request auth error: ", error));

query

必需属性是 startDataendDatedataTypedataType 必须是 '可用的数据类型' 之一。

默认情况下,数据不会聚合,因此返回所有单个数据点。然而,此插件提供了一种通过 hourdaysourceAndDay 聚合数据的方法,后者将允许您按来源(Fitbit、Nike Run Club、手动输入等)读取每日数据。

如果您在运行 query 之前没有运行 requestAuthorization,则插件会为您(针对请求的 dataType)运行 requestAuthorization。欢迎!😉

this.fitness.query(
{
startDate: new Date(new Date().getTime() - 3 * 24 * 60 * 60 * 1000), // 3 days ago
endDate: new Date(), // now
dataType: "steps", // equal to the 'name' property of 'FitnessType'
unit: "count", // make sure this is compatible with the 'dataType' (see below)
aggregateBy: "day", // optional, one of: "hour", "day", "sourceAndDay"
sortOrder: "desc" // optional, default "asc"
})
.then(result => console.log(JSON.stringify(result)))
.catch(error => this.resultToShow = error);

queryAggregateData 实验!

《query》与《queryAggregateData》的区别:如果您使用《query》,您可能会发现步骤数(或其他类型的数据)与Google Fit和Apple Health应用显示的不匹配。如果您想要准确计算用户数据,则使用《queryAggregateData》。

必需属性是 startDataendDatedataTypedataType 必须是 '可用的数据类型' 之一。

默认情况下,数据按《day》聚合。然而,此插件提供了一种方法来按《hour》和《day》聚合数据。(《month》和《year》即将推出)

请注意,《queryAggregateData》仅支持Android上的《steps》、《calories》和《distance》。(更多数据类型即将推出)

如果您在运行 query 之前没有运行 requestAuthorization,则插件会为您(针对请求的 dataType)运行 requestAuthorization。欢迎!😉

this.fitness.queryAggregateData(
{
startDate: new Date(new Date().getTime() - 3 * 24 * 60 * 60 * 1000), // 3 days ago
endDate: new Date(), // now
dataType: "steps", // equal to the 'name' property of 'FitnessType'
unit: "count", // make sure this is compatible with the 'dataType' (see below)
aggregateBy: "day", // optional, one of: "hour", "day" ; default: "day"
})
.then(result => console.log(JSON.stringify(result)))
.catch(error => this.resultToShow = error);

《startMonitoring》(仅限iOS,目前如此)

如果您想在健康数据更改时收到通知,可以监视特定类型。即使您的应用处于后台,这也适用,只要设置enableBackgroundUpdates: true。请注意,iOS会唤醒您的应用,以便您可以对此通知采取行动(例如,通过在onUpdate函数中查询此数据类型的最近更改),但反过来,您有责任通知iOS您已完成。因此,请确保按照以下示例调用completionHandler

并非所有数据类型都支持backgroundUpdateFrequency: "immediate",因此您的应用在HealthKit中添加/删除数据时可能不会立即被调用。

后台通知可能在iOS模拟器上不起作用,因此请在实际设备上测试这些功能。

this.fitness.startMonitoring(
{
dataType: "heartRate",
enableBackgroundUpdates: true,
backgroundUpdateFrequency: "immediate",
onUpdate: (completionHandler: () => void) => {
console.log("Our app was notified that health data changed, so querying...");
this.getData("heartRate", "count/min").then(() => completionHandler());
}
})
.then(() => this.resultToShow = `Started monitoring heartRate`)
.catch(error => this.resultToShow = error);

《stopMonitoring》(仅限iOS,目前如此)

如果您不再希望接收健康数据更改的通知,最好调用此方法。

this.fitness.stopMonitoring(
{
dataType: "heartRate",
})
.then(() => this.resultToShow = `Stopped monitoring heartRate`)
.catch(error => this.resultToShow = error);

可用数据类型

在版本1.0.0中,以下是可以读取的数据支持的类型。同时,请确保传入正确的unit

请注意,您有责任传入正确的unit,尽管每种类型只有一个选项。实际上,目前Android上忽略unit,而在iOS上有未记录的类型可以传入(例如,mi用于distance)。

原因是我想为每种类型支持更多单位,但这尚未实现...所以这是为了未来的向后兼容性!🤯

数据类型类型 单位 GoogleFit数据类型 Apple HealthKit数据类型
distance m TYPE_DISTANCE_DELTA HKQuantityTypeIdentifierDistanceWalkingRunning
steps count TYPE_STEP_COUNT_DELTA HKQuantityTypeIdentifierStepCount
calories count TYPE_CALORIES_EXPENDED HKQuantityTypeIdentifierActiveEnergyBurned
height m TYPE_HEIGHT HKQuantityTypeIdentifierHeight
weight kg TYPE_WEIGHT HKQuantityTypeIdentifierBodyMass
heartRate count/min TYPE_HEART_RATE_BPM HKQuantityTypeIdentifierHeartRate
fatPercentage % TYPE_BODY_FAT_PERCENTAGE HKQuantityTypeIdentifierBodyFatPercentage
cardio min TYPE_HEART_POINTS HKQuantityTypeIdentifierAppleExerciseTime