Home > Back-end >  .NET MAUI Accessing Apple Healthkit
.NET MAUI Accessing Apple Healthkit

Time:12-09

I would like to access iOS Healthkit, eventually Android too but cannot find out a successful way to do it. Online I've seen advice pointing to https://learn.microsoft.com/en-us/xamarin/ios/platform/healthkit which is for xamarin and not MAUI, but the methods in the example are not found. This is the code:

private HKHealthStore healthKitStore = new HKHealthStore ();

public override void OnActivated (UIApplication application)
{
    ValidateAuthorization ();
}

private void ValidateAuthorization ()
{
    var heartRateId = HKQuantityTypeIdentifierKey.HeartRate;
    var heartRateType = HKObjectType.GetQuantityType (heartRateId);
    var typesToWrite = new NSSet (new [] { heartRateType });
    var typesToRead = new NSSet ();
    healthKitStore.RequestAuthorizationToShare (
            typesToWrite, 
            typesToRead, 
            ReactToHealthCarePermissions);
}

void ReactToHealthCarePermissions (bool success, NSError error)
{
    var access = healthKitStore.GetAuthorizationStatus (HKObjectType.GetQuantityType (HKQuantityTypeIdentifierKey.HeartRate));
    if (access.HasFlag (HKAuthorizationStatus.SharingAuthorized)) {
            HeartRateModel.Instance.Enabled = true;
    } else {
            HeartRateModel.Instance.Enabled = false;
    }
}

Unfortunately,

HKQuantityTypeIdentifierKey.HeartRate;
HKObjectType.GetQuantityType (heartRateId);

Seem to be missing. Has anyone got a working example for MAUI?

CodePudding user response:

These two methods in the documentation you refer to are outdated, you can modify your method as follows:

HKQuantityTypeIdentifierKey.HeartRate; ---> HKQuantityTypeIdentifier.HeartRate;

HKObjectType.GetQuantityType (heartRateId); ---> HKQuantityType.Create(heartRateId);

For more details, you can refer to:

HealthKit Namespace | Microsoft

HKQuantityTypeIdentifierKey Class | Microsoft

HKObjectType.GetQuantityType(NSString) Method | Microsoft

  • Related