Condividi tramite


HealthKit Namespace

The HealthKit namespace provides secure data storage and retrieval of health-related information.

Classes

Name Description
HKActivityMoveModeObject
HKActivitySummary

Summarizes user activity for a specific day.

HKActivitySummaryQuery

Gets HKActivitySummary instances that match an NSPredicate.

HKActivitySummaryType

Obect that is used to request permission to read HKActivitySummary objects.

HKAnchoredObjectQuery

An HKQuery that on its initial call returns the most recent result and in subsequent calls returns only data added after the initial call.

HKAppleSleepingBreathingDisturbances
HKAppleWalkingSteadiness
HKAttachment
HKAttachmentStore
HKAudiogramSample
HKAudiogramSampleType
HKAudiogramSensitivityPoint
HKAudiogramSensitivityPointClampingRange
HKAudiogramSensitivityTest
HKBiologicalSexObject

Returned by GetBiologicalSex(NSError).

HKBloodTypeObject

Returned by GetBloodType(NSError)

HKCategorySample

An HKSample whose value is one of an enumerated type.

HKCategoryType

An HKSampleType that currently has only one form: sleep analysis.

HKCategoryTypeIdentifierExtensions

Extension methods for the HKCategoryTypeIdentifier enumeration.

HKCategoryValueSleepAnalysisAsleep
HKCdaDocument

Contains the information that is represented in XML in a HealthKit store health document.

HKCdaDocumentSample

Contains the information that is represented in XML in a HealthKit store health document.

HKCharacteristicType

An HKObjectType that specifies a permanent aspect of the user.

HKCharacteristicTypeIdentifierExtensions

Extension methods for the HKCharacteristicTypeIdentifier enumeration.

HKClinicalCoding
HKClinicalRecord

A sample for clinical records.

HKClinicalType

A sample type for a clinical record.

HKClinicalTypeIdentifierExtensions

Extension methods for the HKClinicalTypeIdentifier enumeration.

HKContactsLensSpecification
HKContactsPrescription
HKCorrelation

A correlation between two pieces of health data (for instance, blood pressure).

HKCorrelationQuery

An HKQuery that returns only data that had been stored with correlations. (Note: Systolic and diastolic blood pressure readings are not correlated.)

HKCorrelationType

An HKSampleType that specifies a correlation between two types of data (for instance, blood pressure).

HKCorrelationTypeIdentifierExtensions

Extension methods for the HKCorrelationTypeIdentifier enumeration.

HKCumulativeQuantitySample
HKCumulativeQuantitySeriesSample

A cumulative data series.

HKDataTypeIdentifierExtensions

Extension methods for the HKDataTypeIdentifier enumeration.

HKDeletedObject

Represents samples that have been deleted from the store.

HKDetailedCdaErrors
HKDevice

Hardware that generates or consumes HealthKit data.

HKDevicePropertyKey

Holds keys whose constant values relate to properties of a HKDevice.

HKDiscreteQuantitySample
HKDocumentQuery

Queries for documents in the HealthKit store.

HKDocumentSample

Abstract HealthKit store health document.

HKDocumentType

Contains a constant that identifies the CDA document type.

HKDocumentTypeIdentifierExtensions

Extension methods for the HKDocumentTypeIdentifier enumeration.

HKElectrocardiogram
HKElectrocardiogramQuery
HKElectrocardiogramType
HKElectrocardiogramVoltageMeasurement
HKErrorCodeExtensions

Extension methods for the HKErrorCode enumeration.

HKFhirReleaseExtensions

Extension methods for the HKFhirRelease enumeration.

HKFhirResource

Represents a Fast Healthcare Interoperability Resources (FHIR) resource.

HKFhirResourceTypeExtensions

Extension methods for the HKFhirResourceType enumeration.

HKFhirVersion
HKFitzpatrickSkinTypeObject

Holds skin-type data.

HKGad7Assessment
HKGlassesLensSpecification
HKGlassesPrescription
HKHealthConceptDomainExtensions

Extension methods for the HKHealthConceptDomain enumeration.

HKHealthConceptIdentifier
HKHealthStore

MonoTouch.HealthKit.HKHealthStore A connection to the system-wide database of health-related information.

HKHealthStore_HKWorkoutRelationship
HKHealthStore.Notifications

Notifications posted by the HKHealthStore class.

HKHeartbeatSeriesBuilder
HKHeartbeatSeriesQuery
HKHeartbeatSeriesSample
HKLensSpecification
HKLiveWorkoutBuilder
HKLiveWorkoutBuilderDelegate

This is a class that implements the interface IHKLiveWorkoutBuilderDelegate (for the protocol HKLiveWorkoutBuilderDelegate).

Subclass this class to easily create a type that implements the protocol.

An alternative is to create a subclass of NSObject and then implemented the interface IHKLiveWorkoutBuilderDelegate.

HKLiveWorkoutBuilderDelegate_Extensions

Extension methods to the IHKLiveWorkoutBuilderDelegate interface to support all the methods from the HKLiveWorkoutBuilderDelegate protocol.

HKLiveWorkoutDataSource
HKMedicationConcept
HKMedicationDoseEvent
HKMedicationDoseEventType
HKMedicationGeneralFormExtensions

Extension methods for the HKMedicationGeneralForm enumeration.

HKMetadata

A key-value store for various types of health-related metadata.

HKMetadataKey

Defines the keys in the HKMetadata key-value dictionary.

HKObject

Base class to HKSample, which defines sampling data.

HKObjectType

Base class for types of data storable in the Health Kit database.

HKObserverQuery

An HKQuery that runs once initially and then is automatically executed when relevant data is added to the database .

HKPhq9Assessment
HKPredicateKeyPath

Contains constants that represent keys that identify predicate key paths for selecting HealthKit values.

HKPrescriptionType
HKQuantity

Represents a measurable quantity of a certain type of unit, with a double value and a HKUnit type.

HKQuantitySample

A HKSample that has a magnitude (see Quantity).

HKQuantitySeriesSampleBuilder

Builds quantity sample series.

HKQuantitySeriesSampleQuery

Queries series data in a quantity sample.

HKQuantityType

A HKSampleType that represents either a cumulative or discrete sample.

HKQuantityTypeIdentifierExtensions

Extension methods for the HKQuantityTypeIdentifier enumeration.

HKQuery

Base class for querying Health Kit databases.

HKQueryAnchor

Represents the most recent sample that was returned by a previous anchored object query.

HKQueryDescriptor
HKSample

A measurement of health information. Base class for HKQuantitySample and HKCategorySample.

HKSampleQuery

An HKQuery that retrieves HKSampleType data from the database.

HKSampleType

An HKObject that represents data that is sampled at a specific time or sampled over a time period.

HKScoredAssessment
HKScoredAssessmentType
HKScoredAssessmentTypeIdentifierExtensions

Extension methods for the HKScoredAssessmentTypeIdentifier enumeration.

HKSeriesBuilder
HKSeriesSample
HKSeriesType
HKSource

A provider of health data, such as a particular sensor or application.

HKSourceQuery

Class that represents a query for HealthKit data.

HKSourceRevision

Wraps HKSource, adding version information.

HKSourceRevisionInfo
HKStateOfMind
HKStateOfMindType
HKStateOfMindValence

This class contains helper functions for the HKStateOfMindValenceClassification enum.

HKStatistics

Provides basic statistical operations on health information.

HKStatisticsCollection

A group of related statistics (generally representing a time series).

HKStatisticsCollectionQuery

An HKQuery that produces a collection of statistics (for instance, number of steps per day for the previous month).

HKStatisticsQuery

An HKQuery that can calculate basic statistics (such as the sum and mean) on its constituent data.

HKUnit

Definitions and utility methods for manipulating measurements of mass, length, volume, and energy.

HKUserAnnotatedMedication
HKUserAnnotatedMedicationPredicateKeyPathExtensions

Extension methods for the HKUserAnnotatedMedicationPredicateKeyPath enumeration.

HKUserAnnotatedMedicationQuery
HKUserAnnotatedMedicationType
HKVerifiableClinicalRecord
HKVerifiableClinicalRecordCredentialTypeExtensions

Extension methods for the HKVerifiableClinicalRecordCredentialType enumeration.

HKVerifiableClinicalRecordQuery
HKVerifiableClinicalRecordSourceTypeExtensions

Extension methods for the HKVerifiableClinicalRecordSourceType enumeration.

HKVerifiableClinicalRecordSubject
HKVisionPrescription
HKVisionPrism
HKWheelchairUseObject

Contains an enumeration that describes wheelchair use.

HKWorkout

An HKSample that represents a physical workout.

HKWorkoutActivity
HKWorkoutBuilder

Builds a workout from workout data as it is added.

HKWorkoutConfiguration

Contains workout configuration information.

HKWorkoutEffortRelationship
HKWorkoutEffortRelationshipQuery
HKWorkoutEvent

A pause or resumption of a workout.

HKWorkoutRoute
HKWorkoutRouteBuilder

A class for adding geographical data to a workout as the user's location changes.

HKWorkoutRouteQuery
HKWorkoutSession
HKWorkoutSessionDelegate

This is a class that implements the interface IHKWorkoutSessionDelegate (for the protocol HKWorkoutSessionDelegate).

Subclass this class to easily create a type that implements the protocol.

An alternative is to create a subclass of NSObject and then implemented the interface IHKWorkoutSessionDelegate.

HKWorkoutSessionDelegate_Extensions

Extension methods to the IHKWorkoutSessionDelegate interface to support all the methods from the HKWorkoutSessionDelegate protocol.

HKWorkoutType

An HKSampleType representing a workout.

Interfaces

Name Description
IHKLiveWorkoutBuilderDelegate

This interface represents the Objective-C protocol HKLiveWorkoutBuilderDelegate.

IHKWorkoutSessionDelegate

This interface represents the Objective-C protocol HKWorkoutSessionDelegate.

Enums

Name Description
HKActivityMoveMode
HKAppleEcgAlgorithmVersion
HKAppleSleepingBreathingDisturbancesClassification
HKAppleWalkingSteadinessClassification
HKAudiogramConductionType
HKAudiogramSensitivityTestSide
HKAuthorizationRequestStatus

Enumerates values that tell when an app should request user permission for access.

HKAuthorizationStatus

Enumerates the permission of the app to read or write health data.

HKBiologicalSex

Enumerates the biological sexes.

HKBloodGlucoseMealTime

Enumerates values that tell whether a blood glucose level was taken before or after a meal.

HKBloodType

Enumerates known blood types.

HKBodyTemperatureSensorLocation

Enumerates the positions at which a thermometer takes its reading.

HKCategoryTypeIdentifier

Enumerates the types of HKCategoryTypes.

HKCategoryValue

Contains a single value that indicates that a category value is not applicable to the category.

HKCategoryValueAppetiteChanges
HKCategoryValueAppleStandHour

Enumerates whether the user stood or not during an hour.

HKCategoryValueAppleWalkingSteadinessEvent
HKCategoryValueAudioExposureEvent
HKCategoryValueCervicalMucusQuality

Enumerates the user's cervical mucus quality.

HKCategoryValueContraceptive
HKCategoryValueEnvironmentalAudioExposureEvent
HKCategoryValueHeadphoneAudioExposureEvent
HKCategoryValueLowCardioFitnessEvent
HKCategoryValueMenstrualFlow

Enumerates the amount of menstrual flow.

HKCategoryValueOvulationTestResult

Enumerates the results of an ovulation test.

HKCategoryValuePregnancyTestResult
HKCategoryValuePresence
HKCategoryValueProgesteroneTestResult
HKCategoryValueSeverity
HKCategoryValueSleepAnalysis

Enumerates the states of the slumberer: whether they are asleep or merely resting in bed.

HKCategoryValueVaginalBleeding
HKCharacteristicTypeIdentifier

Enumerates the forms of HKCharacteristicType.

HKClinicalTypeIdentifier

Enumerates clinical record type identifiers.

HKCorrelationTypeIdentifier

Contains constants that identify HealthKit correlation types.

HKCyclingFunctionalThresholdPowerTestType
HKDataTypeIdentifier
HKDevicePlacementSide
HKDocumentTypeIdentifier

Enumerates HealthKit document types.

HKElectrocardiogramClassification
HKElectrocardiogramLead
HKElectrocardiogramSymptomsStatus
HKErrorCode

Enumerates common errors made when accessing health data.

HKFhirRelease
HKFhirResourceType

Enumerates Fast Healthcare Interoperability Resources (FHIR) types.

HKFitzpatrickSkinType

Enumerates skin types using the Fitzpatrick scale.

HKGad7AssessmentAnswer
HKGad7AssessmentRisk
HKHealthConceptDomain
HKHeartRateMotionContext

Enumerates the possible activity-levels associated with a heart-rate sample.

HKHeartRateRecoveryTestType
HKHeartRateSensorLocation

Enumerates the locations at which a heart rate monitor is attached.

HKInsulinDeliveryReason

Enumerates the reasons for why insulin was provided.

HKMedicationDoseEventLogStatus
HKMedicationDoseEventScheduleType
HKMedicationGeneralForm
HKMetricPrefix

Enumerates metric prefixes, e.g., Centi-, Deca-, Deci-. Used with factory methods of HKUnit.

HKPhq9AssessmentAnswer
HKPhq9AssessmentRisk
HKPhysicalEffortEstimationType
HKPrismBase
HKQuantityAggregationStyle

Enumerates whether an HKQuantityType is a cumulative measure (for instance, "active energy burned") or a discrete value (such as "blood alcohol content").

HKQuantityTypeIdentifier

Enumerates the types of HKQuantityType.

HKQueryOptions

Enumerates options available for use with the GetPredicateForSamples(NSDate, NSDate, HKQueryOptions) method.

HKScoredAssessmentTypeIdentifier
HKStateOfMindAssociation
HKStateOfMindKind
HKStateOfMindLabel
HKStateOfMindValenceClassification
HKStatisticsOptions

Enumerates options applicable to HKStatisticsQuery and HKStatisticsCollectionQuery objets.

HKSwimmingStrokeStyle
HKUpdateFrequency

Enumerates the frequences for background delivery of data (see EnableBackgroundDelivery(HKObjectType, HKUpdateFrequency, Action<Boolean,NSError>)).

HKUserAnnotatedMedicationPredicateKeyPath
HKUserMotionContext
HKVerifiableClinicalRecordCredentialType
HKVerifiableClinicalRecordSourceType
HKVisionEye
HKVisionPrescriptionType
HKVO2MaxTestType

Enumerates the testing process used for establishing VO2 Max.

HKWaterSalinity
HKWeatherCondition

Enumerates weather types.

HKWheelchairUse

Enumerates constants that describe wheelchair use.

HKWorkoutActivityType

Enumerates various activities that are considered workouts.

HKWorkoutEffortRelationshipQueryOptions
HKWorkoutEventType

Enumerates events that can occur during a workout (Pause, Resume).

HKWorkoutSessionLocationType

Enumerates workout locations.

HKWorkoutSessionState
HKWorkoutSessionType
HKWorkoutSwimmingLocationType

Delegates

Name Description
HKAnchoredObjectResultHandler

The completion handler for HKAnchoredObjectQuery(HKSampleType, NSPredicate, UIntPtr, UIntPtr, HKAnchoredObjectResultHandler).

HKAnchoredObjectUpdateHandler
HKAttachmentStoreCompletionHandler
HKAttachmentStoreDataHandler
HKAttachmentStoreGetAttachmentCompletionHandler
HKCorrelationQueryResultHandler

Completion handler for HKCorrelationQuery.

HKElectrocardiogramQueryDataHandler
HKHealthStoreCompletionHandler
HKHealthStoreGetRequestStatusForAuthorizationToShareHandler

Handler to pass to GetRequestStatusForAuthorizationToShare(NSSet<HKSampleType>, NSSet<HKObjectType>, HKHealthStoreGetRequestStatusForAuthorizationToShareHandler).

HKHealthStoreRecoverActiveWorkoutSessionHandler
HKHeartbeatSeriesBuilderCompletionHandler
HKHeartbeatSeriesQueryDataHandler
HKObserverQueryDescriptorUpdateHandler
HKObserverQueryUpdateHandler

Update handler for HKObserverQuery objects.

HKQuantitySeriesSampleBuilderFinishSeriesDelegate

Completion handler for FinishSeries(NSDictionary, HKQuantitySeriesSampleBuilderFinishSeriesDelegate).

HKQuantitySeriesSampleQueryQuantityDelegate

A handler to pass to HKQuantitySeriesSampleQuery(HKQuantitySample, HKQuantitySeriesSampleQueryQuantityDelegate).

HKQuantitySeriesSampleQueryQuantityHandler
HKSampleQueryResultsHandler

Result handler for HKSampleQuery.

HKSourceQueryCompletionHandler

Completion handler for HKSourceQuery.

HKStatisticsCollectionEnumerator

Delegate handler for EnumerateStatistics(NSDate, NSDate, HKStatisticsCollectionEnumerator).

HKStatisticsCollectionQueryInitialResultsHandler

The delegate for InitialResultsHandler.

HKStatisticsCollectionQueryStatisticsUpdateHandler

The delegate for StatisticsUpdated.

HKStatisticsQueryHandler

Results handler for HKStatisticsQuery.

HKStoreSampleAddedCallback

Completion handler for AddSamples(HKSample[], HKWorkout, HKStoreSampleAddedCallback).

HKUserAnnotatedMedicationQueryCallback
HKVerifiableClinicalRecordQueryResultHandler
HKWorkoutBuilderCompletionHandler

Completion handler for adding metadata with HKWorkoutRouteQuery(HKWorkoutRoute, HKWorkoutRouteBuilderDataHandler).

HKWorkoutEffortRelationshipQueryResultsHandler
HKWorkoutRelationshipCallback
HKWorkoutRouteBuilderAddMetadataHandler

Completion handler for adding metadata with HKWorkoutRouteQuery(HKWorkoutRoute, HKWorkoutRouteBuilderDataHandler).

HKWorkoutRouteBuilderDataHandler
HKWorkoutRouteQueryDataHandler

Remarks

The HealthKit namespace allows applications to record, track, and access health-related information to a common persistent store.

Provisioning, Permissions, and Profiles

To use HealthKit services, applications must be developed using an "Explicit App ID" and a provisioning profile that includes the explicit ID and HealthKit 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.

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 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 GetAuthorizationStatus method:

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 HKSample of a particular HKSampleType and then calling SaveObject or 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 RequestAuthorizationToShare and SaveObject are defined with completion callback handlers that are passed a non-null 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, .NET's asynchronous versions of such methods (such as RequestAuthorizationToShareAsync and SaveObjectAsync) will throw an NSErrorException on failure or if the method is not allowed by the end user.

//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...
  }
// .NET'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 HKObjectTypes:

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

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

HKSamples may refer to an instantaneous measurement, in which case their StartDate and 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 HKMetadataKey, but application developers are encouraged to create their own keys for metadata as well.

Units of measurement and conversion

HealthKit 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:

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