MonoTouch.HealthKit Namespace

Records and tracks health-related information.

Remarks

The Health Kit namespace, introduced in iOS 8, allows applications to record, track, and access health-related information to a common persistent store.

Provisioning, Permissions, and Profiles

To use Health Kit services, applications must be developed using an "Explicit App ID" and a provisioning profile that includes the explicit ID and Health Kit permissions.

In addition, applications must have an Entitlements.plist that contains the key com.apple.developer.healthkit of type Boolean with a value of true.

At runtime, the application must request access to the specific types of health data in which it is interested. The user will interact with a permissions dialog in the Health app that allows them fine-grained control over what health information they will allow.

C# Example

var temperatureKey = HKQuantityTypeIdentifierKey.BodyTemperature;
var tempQuantityType = HKObjectType.GetQuantityType (temperatureKey);

var hks = new HKHealthStore ();
var success = await hks.RequestAuthorizationToShareAsync (new NSSet (new [] { tempQuantityType }), new NSSet ());
        
          

The result of the MonoTouch.HealthKit.HKHealthStore.RequestAuthorizationtoShareAsync method indicates only that the user interacted with the permissions dialog, it does not indicate whether the user allowed any data sharing. For that, applications can use the MonoTouch.HealthKit.HKHealthStore.GetAuthorizationStatus method:

C# Example

var access = healthKitStore.GetAuthorizationStatus (HKObjectType.GetQuantityType (HKQuantityTypeIdentifierKey.HeartRate));
if (access.HasFlag (HKAuthorizationStatus.SharingAuthorized)) {
//...etc...
          

Creating and storing data

Once permissions have been granted, creating and storing data involves creating an MonoTouch.HealthKit.HKSample of a particular MonoTouch.HealthKit.HKSampleType and then calling MonoTouch.HealthKit.HKHealthStore.SaveObject or MonoTouch.HealthKit.HKHealthStore.SaveObjectAsync.

Exception-handling differences between async and non-async methods

Apple's philosophy regarding attempts to store or read non-permitted information is that such attempts should not cause runtime exceptions. Rather, methods such as MonoTouch.HealthKit.HKHealthStore.RequestAuthorizationToShare and MonoTouch.HealthKit.HKStore.SaveObject are defined with completion callback handlers that are passed a non-null MonoTouch.Foundation.NSError argument in the case of an error. Application developers using such methods should take special care to check for success, as it is highly likely that users will be cautious about access to their health data.

In contrast, Xamarin's asynchronous versions of such methods (such as MonoTouch.HealthKit.HKHealthStore.RequestAutorizationToShareAsync and MonoTouch.HealthKit.HKHealthStore.SaveObjectAsync) will throw an MonoTouch.Foundation.NSErrorException on failure or if the method is not allowed by the end user.

C# Example

//Apple's philosophy: no exception
var myCurrentTemp = HKQuantity.FromQuantity (HKUnit.DegreeFahrenheit, 98.6);
var tempSample = HKQuantitySample.FromType (tempQuantityType, myCurrentTemp, new NSDate (), new NSDate (), new NSDictionary());

hks.SaveObject(tempSample, (success, error) => {
	if(error != null)
	{
   //...etc...
          

C# Example

//Xamarin's philosophy: Lack of permissions raises exception
protected async void StoreAsync(HKHealthStore store, HKQuantitySample sample)
{
	try
	{
		var success = await store.SaveObjectAsync (sample);

	}catch(NSErrorException x)
	{
		Console.WriteLine (x);
	}
}
          

There are several types of MonoTouch.HealthKit.HKObjecTypes:

MonoTouch.HealthKit.HKCharacteristicType objects represent static characterics of the user, such as date of birth or blood type (see MonoTouch.HealthKit.HKCharacteristicTypeIdentifierKey), while MonoTouch.HealthKit.HKSampleType objects represent data that are sampled over time. As of iOS 8, there is only one type of MonoTouch.HealthKit.HKCategorySample, which is MonoTouch.HealthKit.HKCategoryTypeIdentifierKey.SleepAnalysis. The large majority of Health Kit data types are defined in MonoTouch.HealthKit.HKQuantityTypeIdentifierKey.

Manipulating data samples involves both an MonoTouch.HealthKit.HKSampleType object and an MonoTouch.HealthKit.HKSample to carry the data:

MonoTouch.HealthKit.HKQuantitySamples may refer to an instantaneous measurement, in which case their MonoTouch.HealthKit.HKQuantitySample.StartDate and MonoTouch.HealthKit.HKQuantitySample.EndDate properties should be set to the same value. Other samples, such as step count, are measured over time and the start and end time should be set appropriately.

Data may have metadata associated with it. There are a number of predefined metadata keys in MonoTouch.HealthKit.HKMetadataKey, but application developers are encouraged to created their own keys for metadata as well.

Units of measurement and conversion

Health Kit supports units of measurement in the categories of mass, length, volume, and energy. This support includes conversion of values between measurement systems (for instance, if a user prefers Fahrenheit degrees but has a sensor that reports its data in Celsius). This is automatically supported within the Health app, but explicit conversions are also possible, as shown in the following example:

C# Example

var myFahrenheitTemp = HKQuantity.FromQuantity (HKUnit.DegreeFahrenheit, 98.6);
var myCelsiusTemp = myFahrenheitTemp.GetDoubleValue (HKUnit.DegreeCelsius);
          

Classes

TypeReason
HKAnchoredObjectQueryAn MonoTouch.HealthKit.HKQuery that on its initial call returns the most recent result and in subsequent calls returns only data added after the initial call.
HKAnchoredObjectResultHandlerThe completion handler for MonoTouch.HealthKit.HKAnchoredObjectQuery.ctor.
HKAnchoredObjectResultHandler2Completion handler for anchored object queries.
HKAuthorizationStatusEnumerates the permission of the app to read or write health data.
HKBiologicalSexEnumerates the biological sexes.
HKBiologicalSexObjectReturned by MonoTouch.HealthKit.HKHealthStore.GetBiologicalSex.
HKBloodTypeEnumerates known blood types.
HKBloodTypeObjectReturned by MonoTouch.HealthKit.HKHealthStore.GetBloodType
HKBodyTemperatureSensorLocationEnumerates the positions at which a thermometer takes its reading.
HKCategorySampleAn MonoTouch.HealthKit.HKSample whose value is one of an enumerated type.
HKCategoryTypeAn MonoTouch.HealthKit.HKSampleType that currently has only one form: sleep analysis.
HKCategoryTypeIdentifierEnumerates the types of MonoTouch.HealthKit.HKCategory; currently there is only the one form (Sleep Analysis).
HKCategoryTypeIdentifierKeyDefines the keys to identify MonoTouch.HealthKit.HKCategoryTypes. Currently just the one key for sleep analysis.
HKCategoryValueSleepAnalysisEnumerates the states of the slumberer: whether they are asleep or merely resting in bed.
HKCharacteristicTypeAn MonoTouch.HealthKit.HKObjectType that specifies a permanent aspect of the user.
HKCharacteristicTypeIdentifierEnumerates the forms of MonoTouch.HealthKit.HKCharacteristicType.
HKCharacteristicTypeIdentifierKeyDefines the constant name for a MonoTouch.HealthKit.HKCharacteristicType.
HKCorrelationA correlation between two pieces of health data (for instance, blood pressure).
HKCorrelationQueryAn MonoTouch.HealthKit.HKQuery that returns only data that had been stored with correlations. (Note: Systolic and diastolic blood pressure readings are not correlated.)
HKCorrelationQueryResultHandlerCompletion handler for MonoTouch.HealthKit.HKCorrelationQuery.
HKCorrelationTypeAn MonoTouch.HealthKit.HKSampleType that specifies a correlation between two types of data (for instance, blood pressure).
HKCorrelationTypeKeyDefines the forms of MonoTouch.HealthKit.HKCorrelation.
HKErrorCodeEnumerates common errors made when accessing health data.
HKHealthStoreMonoTouch.HealthKit.HKHealthStore A connection to the system-wide database of health-related information.
HKHealthStore+NotificationsClass that contains handlers for Health Kit store notifications.
HKHeartRateSensorLocationEnumerates the locations at which a heart rate monitor is attached.
HKMetadataA key-value store for various types of health-related metadata.
HKMetadataKeyDefines the keys in the MonoTouch.HealthKit.HKMetadata key-value dictionary.
HKMetricPrefixEnumerates metric prefixes, e.g., Centi-, Deca-, Deci-. Used with factory methods of MonoTouch.HealthKit.HKUnit.
HKObjectBase class to MonoTouch.HealthKit.HKSample, which defines sampling data.
HKObjectTypeBase class for types of data storable in the Health Kit database.
HKObserverQueryAn MonoTouch.HealthKit.HKQuery that runs once initially and then is automatically executed when relevant data is added to the database .
HKObserverQueryUpdateHandlerUpdate handler for MonoTouch.HealthKit.HKObserverQuery objects.
HKPredicateKeyPathContains constants that represent keys that identify predicate key paths for selecting HealthKit values.
HKQuantityRepresents a measurable quantity of a certain type of unit, with a double value and a MonoTouch.HealthKit.HKUnit type.
HKQuantityAggregationStyleEnumerates whether an MonoTouch.HealthKit.HKQuantityType is a cumulative measure (for instance, "active energy burned") or a discrete value (such as "blood alcohol content").
HKQuantitySampleA MonoTouch.HealthKit.HKSample that has a magnitude (see MonoTouch.HealthKit.HKQuantitySample.Quantity).
HKQuantityTypeA MonoTouch.HKSampleType that represents either a cumulative or discrete sample.
HKQuantityTypeIdentifierEnumerates the types of MonoTouch.HealthKit.HKQuantityType.
HKQuantityTypeIdentifierKeyTypes of MonoTouch.HealthKit.HKQuantityType.
HKQueryBase class for querying Health Kit databases.
HKQueryOptionsEnumerates options available for use with the MonoTouch.HKQuery.GetPredicateForSamples method.
HKSampleA measurement of health information. Base class for MonoTouch.HealthKit.HKQuantitySample and MonoTouch.HealthKit.HKCategorySample.
HKSampleQueryAn MonoTouch.HealthKit.HKQuery that retrieves MonoTouch.HealthKit.HKSampleType data from the database.
HKSampleQueryResultsHandlerResult handler for MonoTouch.HealthKit.HKSampleQuery.
HKSampleTypeAn MonoTouch.HealthKit.HKObject that represents data that is sampled at a specific time or sampled over a time period.
HKSourceA provider of health data, such as a particular sensor or application.
HKSourceQueryClass that represents a query for HealthKit data.
HKSourceQueryCompletionHandlerCompletion handler for MonoTouch.HealthKit.HKSourceQuery.
HKStatisticsProvides basic statistical operations on health information.
HKStatisticsCollectionA group of related statistics (generally representing a time series).
HKStatisticsCollectionEnumeratorDelegate handler for MonoTouch.HealthKit.HKStatisticsCollection.EnumerateStatistics.
HKStatisticsCollectionQueryAn MonoTouch.HealthKit.HKQuery that produces a collection of statistics (for instance, number of steps per day for the previous month).
HKStatisticsCollectionQueryInitialResultsHandlerResults handler for MonoTouch.HealthKit.HKStatisticsCollectionQuery.SetInitialResultsHandler and MonoTouch.HealthKit.HKStatisticsCollectionQuery.SetStatisticsUpdateHandler.
HKStatisticsOptionsEnumerates options applicable to MonoTouch.HealthKit.HKStatisticsQuery and MonoTouch.HealthKit.HKStatisticsCollectionQuery objets.
HKStatisticsQueryAn MonoTouch.HealthKit.HKQuery that can calculate basic statistics (such as the sum and mean) on its constituent data.
HKStatisticsQueryHandlerResults handler for MonoTouch.HKStatisticsQuery.
HKStoreSampleAddedCallbackCompletion handler for MonoTouch.HealthKit.HKHealthStore.AddSamples.
HKUnitDefinitions and utility methods for manipulating measurements of mass, length, volume, and energy.
HKUpdateFrequencyEnumerates the frequences for background delivery of data (see MonoTouch.HealthKit.HKHealthStore.EnableBackgroundDelivery).
HKWorkoutAn MonoTouch.HealthKit.HKSample that represents a physical workout.
HKWorkoutActivityTypeEnumerates various activities that are considered workouts.
HKWorkoutEventA pause or resumption of a workout.
HKWorkoutEventTypeEnumerates events that can occur during a workout (Pause, Resume).
HKWorkoutTypeAn MonoTouch.HealthKit.HKSampleType representing a workout.