Авторизація даних здоров’я в мобільній розробці: що це таке, як працює та доступ до HealthKit

Автор: IT Sectr Опубліковано: 2026-05-22 Час читання: 8 хв

Авторизація даних здоров’я — це процес отримання явної згоди користувача на читання та запис медичних та фітнес-даних через системні API мобільних платформ. На iOS авторизація реалізована через HealthKit з класами HKHealthStore та HKObjectType, тоді як на Android вона виконується через Google Fit API з OAuth 2.0 та FitnessOptions. According to the Apple HealthKit Documentation, 2025, health data is classified as a category of highly sensitive information. Medical accuracy and regulatory compliance are key requirements when working with such data.

Ключові моменти

  • Health Data Authorization is a mandatory process of obtaining consent to access user medical data.
  • HealthKit is Apple's framework for working with health data, including HKHealthStore and HKObjectType.
  • Google Fit API is an Android platform for accessing fitness data via OAuth 2.0 and FitnessOptions.
  • HKHealthStore is the central iOS class for requesting authorization and performing operations with health data.
  • User consent is a mandatory step where the user selects specific data types to grant access to.

Що таке авторизація даних здоров’я?

Health data authorization is a mechanism that requires explicit and documented user consent before accessing their medical and fitness metrics. Unlike standard permissions (contacts, calendar), health data is governed by additional legal regulations: HIPAA in the US, GDPR in Europe, and Federal Law 152-FZ in Росія.

On iOS, health authorization is implemented through HealthKit: the user sees a screen listing all types of data the application requests and can select specific categories to grant access. On Android, Google Fit API is used with OAuth 2.0 authorization, where a separate scope is requested for each data type.

According to App Annie (2025), health and fitness applications are one of the fastest growing segments of the mobile market with an annual growth rate of 28%. Meanwhile, 71% of users deny access to health data if the application does not provide a clear explanation of the purpose of collection.

Key difference of health authorization from other permissions is the ability to grant partial access. A user can allow reading steps but prohibit access to heart rate data or medical records.

Як HealthKit працює на iOS

HealthKit is Apple's framework, introduced in iOS 8, that provides a unified centralized health data repository. Applications do not have direct access to HealthKit — they request authorization through HKHealthStore, and the user decides which data types to provide. All data is encrypted on the device and synchronized through iCloud with end-to-end encryption.

Запит доступу до HealthKit

The authorization process begins with creating an instance of HKHealthStore and calling the requestAuthorization(toShare:read:) method. The application passes two sets of types: types to read (HKObjectType that the application wants to read) and types to write (HKSampleType that the application wants to save). The system displays a consent screen where the user enables or disables each type individually.

An important feature: HealthKit does not show the developer which specific types the user allowed on the consent screen. After calling requestAuthorization, it is necessary to individually check access to each type via HKHealthStore.authorizationStatus(for:). According to WWDC Session 11108 (2024), Apple recommends checking authorization status before every read or write operation.

HKObjectType Data Types

HealthKit supports hundreds of data types divided into categories: quantity (steps, heart rate, calories), characteristics (height, weight, date of birth), clinical records (allergies, vaccinations, lab results), symptoms, and menstrual cycle. Each type is represented by a subclass of HKObjectType: HKQuantityType for numeric measurements and HKCategoryType for categorical data.

With iOS 18, Apple expanded HealthKit to support data from medical institutions via FHIR (Fast Healthcare Interoperability Resources). Applications can request access to structured medical records if the user has connected their hospital or clinic to the Health app.

Як Google Fit API працює на Android

Google Fit is a platform for working with fitness data on Android that uses OAuth 2.0 authorization. Unlike HealthKit, Google Fit is not built into the OS at the system level — it is a separate Google Play Services service that requires setup through Google Play Console and creation of OAuth 2.0 credentials.

Google Fit та OAuth 2.0

To access Google Fit, the application must register an OAuth 2.0 client ID in Google Cloud Console. Authorization is requested via GoogleSignInAccount and GoogleSignIn.requestPermissions(). The user sees the standard Google consent screen listing the requested scopes: fitness.activity.read, fitness.body.read, fitness.nutrition.write, and others.

Google Fit separates permissions into read and write for each data type. An application can request access to read step count without requesting write permissions. Starting with Google Fit API v2, all authorization requests must include a description of the purpose of data usage — without this, the request is rejected by Google moderation.

FitnessOptions та обсяги

The FitnessOptions class allows declaratively specifying which data types require access. For each type, the access level can be set: ACCESS_READ, ACCESS_WRITE, or both. The permission set is passed to GoogleSignin.requestPermissions() along with the user account.

The list of available types includes: steps (DataType.TYPE_STEP_COUNT_DELTA), calories (TYPE_CALORIES_EXPENDED), heart rate (TYPE_HEART_RATE_BPM), distance (TYPE_DISTANCE_DELTA), activity (TYPE_ACTIVITY_SEGMENT), and sleep (TYPE_SLEEP_SEGMENT). Each type has its own update frequency and permission requirements.

Приклади коду для доступу до даних здоров’я

The implementation of health data authorization requests differs significantly between iOS and Android. Below are working examples for HealthKit and Google Fit API.

HealthKit у Swift

In Swift, the HealthKit authorization request is performed through HKHealthStore by specifying the types to read and write. The example demonstrates requesting access to step count and heart rate data.

swift
import HealthKit

let healthStore = HKHealthStore()

let readTypes: Set<HKObjectType> = [
    HKObjectType.quantityType(forIdentifier: .stepCount)!,
    HKObjectType.quantityType(forIdentifier: .heartRate)!
]

let writeTypes: Set<HKSampleType> = [
    HKObjectType.quantityType(forIdentifier: .stepCount)!
]

guard HKHealthStore.isHealthDataAvailable() else {
    fatalError("HealthKit недоступний на цьому пристрої")
}

healthStore.requestAuthorization(toShare: writeTypes, read: readTypes) { success, error in
    if success {
        // Перевірка статусу кожного типу окремо
        let status = healthStore.authorizationStatus(for: readTypes.first!)
        print("Авторизація HealthKit: \(status.rawValue)")
    } else {
        print("Помилка авторизації HealthKit: \(error?.localizedDescription ?? "неизвестная")")
    }
}

Google Fit у Kotlin

On Android, Google Fit authorization is performed via GoogleSignIn and FitnessOptions. The example demonstrates requesting access to step count and calorie data.

kotlin
val fitnessOptions = FitnessOptions.builder()
    .addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
    .addDataType(DataType.TYPE_CALORIES_EXPENDED, FitnessOptions.ACCESS_READ)
    .build()

val account = GoogleSignIn.getAccountForExtension(this, fitnessOptions)

if (!GoogleSignIn.hasPermissions(account, fitnessOptions)) {
    GoogleSignIn.requestPermissions(
        this,
        REQUEST_GOOGLE_FIT,
        account,
        fitnessOptions
    )
} else {
    // Дозволи вже надано — читання даних
    readGoogleFitData(account)
}

// Обробка результату запиту на дозвіл
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_GOOGLE_FIT && resultCode == RESULT_OK) {
        val account = GoogleSignIn.getSignedInAccountFromIntent(data)
        account?.let { readGoogleFitData(it) }
    }
}

Безпека та відповідність нормативним вимогам

Health data belongs to an especially sensitive category of personal data. Developers of applications working with HealthKit or Google Fit must comply with regulatory requirements in the region of their users.

HIPAA та GDPR для даних здоров’я

In the US, health data is regulated by HIPAA (Health Insurance Portability and Accountability Act), which establishes strict requirements for the storage, transmission, and processing of medical information. Applications working with HealthKit can comply with HIPAA if data is transmitted to the server in encrypted form and access is restricted.

In the European Union, health data is considered a special category of personal data under GDPR (Article 9). Processing such data requires explicit user consent and, in most cases, a data protection impact assessment. Violation of GDPR requirements carries fines of up to 20 million euros or 4% of the company's annual turnover.

In Росія, the collection of health data is regulated by Federal Law 152-FZ “On Personal Data”. Since 2025, all applications processing medical data of Росіяn citizens are required to use certified encryption tools and store data on servers located within the territory of the Росіяn Federation, in accordance with the requirements of Roskomnadzor.

Recommendation: before publishing an application that works with health data, consult with the legal department to verify compliance with local regulations. Apple and Google reserve the right to reject an application if its privacy policy does not meet the requirements.

Часті запитання

What is the difference between HealthKit and Google Fit?

HealthKit is a built-in iOS framework with a local encrypted health data repository. Google Fit is a cloud service based on Google Play Services, using OAuth 2.0 for authorization. HealthKit works offline, Google Fit requires an internet connection for synchronization.

Can a user grant partial access to health data?

Yes, on both platforms. On iOS, the user selects specific data types (steps, heart rate, sleep) on the HealthKit consent screen. On Android, the user sees the list of Google Fit scopes and can revoke individual permissions through Google account settings.

What is HKHealthStore and why is it needed?

HKHealthStore is the central class of the HealthKit framework on iOS. It manages authorization, reading, and writing of all health data. The application cannot directly access the HealthKit repository — all operations go through HKHealthStore, ensuring a unified access interface and compliance with user access rights.

How to revoke Google Fit access for an application?

The user can revoke access through Google Settings — Manage Account — Security — Third-party apps with access. Select the application and click “Remove access”. It is also possible to revoke access through Google Play Console: Connected services — Google Fit — App management.

Is HIPAA compliance mandatory for applications using HealthKit?

If the application processes health data of users in the US and transmits it to a server, HIPAA compliance is mandatory. If all data remains locally on the device and is not transmitted to third parties, the application may not need HIPAA compliance, but Apple recommends following security best practices regardless of jurisdiction.

Підсумок

  • Health Data Authorization is a mandatory process of obtaining explicit user consent to access medical data.
  • HealthKit is Apple's framework for working with health data via HKHealthStore on iOS.
  • Google Fit API is an Android platform for accessing fitness data via OAuth 2.0 and FitnessOptions.
  • Типи даних — HealthKit supports quantitative, categorical, and clinical data; Google Fit supports steps, calories, heart rate, activity, and sleep.
  • Частковий доступ — the user can grant access to some data types while denying others, on both platforms.
  • HIPAA та GDPR — regulatory requirements mandatory when processing health data in the US and European Union.
  • Росіяn regulation — 152-FZ requires certified encryption and data storage on servers in the Росіяn Federation when processing medical data of Росіяn citizens.

Ми розробимо мобільний застосунок під ключ

IT Sectr створює застосунки для iOS та Android для стартапів і бізнесу з 2017 року. Ми проконсультуємо вас і запропонуємо найкраще рішення.

Обговорити проект

Читайте також