You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:.NET MAUI访问Apple HealthKit的可用示例,代码存API缺失问题

.NET MAUI 访问Apple HealthKit 实现示例

你遇到的问题是因为.NET MAUI 采用.NET 6+的iOS绑定,API命名和Xamarin.iOS存在差异:

  • 原HKQuantityTypeIdentifierKey已改为HKQuantityTypeIdentifier枚举
  • 原HKObjectType.GetQuantityType方法已替换为HKQuantityType.Create

以下是完整的可用实现示例:

1. 配置iOS权限

在Platforms/iOS/Info.plist中添加HealthKit权限描述(必须配置,否则授权会失败):

<key>NSHealthShareUsageDescription</key>
<string>需要访问健康数据以同步心率信息</string>
<key>NSHealthUpdateUsageDescription</key>
<string>需要更新健康数据以记录心率信息</string>

2. 平台特定代码实现

在Platforms/iOS目录下修改AppDelegate.cs(或单独创建HealthKit服务类):

using Foundation;
using HealthKit;
using UIKit;

namespace YourAppNamespace.Platforms.iOS;

public partial class AppDelegate : UIApplicationDelegate
{
    private HKHealthStore? _healthKitStore;

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        // 先检查设备是否支持HealthKit
        if (HKHealthStore.IsHealthDataAvailable())
        {
            _healthKitStore = new HKHealthStore();
        }
        return base.FinishedLaunching(application, launchOptions);
    }

    public override void OnActivated(UIApplication application)
    {
        ValidateHealthAuthorization();
        base.OnActivated(application);
    }

    private void ValidateHealthAuthorization()
    {
        if (_healthKitStore == null) return;

        // 使用新的API创建心率类型
        var heartRateType = HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate);
        var typesToShare = new NSSet(new[] { heartRateType });
        var typesToRead = new NSSet(new[] { heartRateType }); // 若只需写入可留空

        _healthKitStore.RequestAuthorizationToShare(typesToShare, typesToRead, (success, error) =>
        {
            if (error != null)
            {
                // 处理授权错误
                return;
            }

            var authorizationStatus = _healthKitStore.GetAuthorizationStatus(heartRateType);
            HeartRateModel.Instance.Enabled = authorizationStatus == HKAuthorizationStatus.SharingAuthorized;
        });
    }
}

关键修改点说明

  • 替换API命名:用HKQuantityTypeIdentifier.HeartRate替代原HKQuantityTypeIdentifierKey.HeartRate
  • 替换类型创建方法:用HKQuantityType.Create()替代原HKObjectType.GetQuantityType()
  • 新增设备兼容性检查:HKHealthStore.IsHealthDataAvailable()避免在不支持HealthKit的设备上崩溃
  • 调整权限范围:根据实际需求配置读写类型集合

后续Android支持提示

Android端可使用Google Fit API实现健康数据访问,需配置对应权限与API密钥,后续可通过MAUI依赖服务统一封装跨平台调用逻辑。

内容的提问来源于stack exchange,提问作者Rob White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:05:23