PyObjC HealthKit Framework

12.1 · active · verified Tue Apr 14

PyObjC-framework-HealthKit provides Python bindings for Apple's HealthKit framework on macOS. It allows Python applications to interact with health and fitness data, offering a bridge to Objective-C APIs. The library is actively maintained with frequent releases, often synchronized with macOS SDK updates and changes in Python version support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to check for HealthKit availability and request authorization to read specific data types (Body Mass and Height). Running this code will trigger a system prompt asking the user for permission. HealthKit operations require an active run loop to handle asynchronous callbacks. For a standalone script, `PyObjCTools.AppHelper.runEventLoop()` is essential to process these callbacks and wait for the authorization request to complete. Note that HealthKit features require an application with the proper entitlements set in Xcode.

import HealthKit
from PyObjCTools import AppHelper

def request_health_authorization():
    if not HealthKit.HKHealthStore.isHealthDataAvailable():
        print("HealthKit is not available on this device.")
        return

    health_store = HealthKit.HKHealthStore.alloc().init()

    # Define types to read and write
    # Example: Body Mass and Height
    try:
        body_mass_type = HealthKit.HKObjectType.quantityTypeForIdentifier_(
            HealthKit.HKQuantityTypeIdentifierBodyMass
        )
        height_type = HealthKit.HKObjectType.quantityTypeForIdentifier_(
            HealthKit.HKQuantityTypeIdentifierHeight
        )
    except Exception as e:
        print(f"Error getting HealthKit object types: {e}")
        return

    types_to_read = {body_mass_type, height_type}
    types_to_share = set() # No data to write in this example

    # Request authorization
    # Note: This will trigger a system prompt to the user
    def completion_handler(success, error):
        if success:
            print("HealthKit authorization granted.")
            # You can now proceed with HealthKit operations
        else:
            print(f"HealthKit authorization denied or error: {error}")
        AppHelper.stopEventLoop()

    health_store.requestAuthorizationToShareTypes_readTypes_completion_(
        types_to_share,
        types_to_read,
        completion_handler
    )


if __name__ == '__main__':
    # Run this from a macOS app context or a script with UI entitlements
    # For a simple script, ensure PyObjCTools.AppHelper.runEventLoop() is used
    # to handle asynchronous callbacks.
    print("Requesting HealthKit authorization...")
    request_health_authorization()
    # For simple scripts where a UI application loop isn't explicitly started,
    # AppHelper.runEventLoop() ensures callbacks are processed.
    # In a full Cocoa app, the app's runloop would handle this.
    AppHelper.runEventLoop()

view raw JSON →