AI-Powered Health Monitoring from Sensor Data
Apple Watch sends 30 heart rate measurements per minute. Fitbit delivers SpO2 every 5 seconds. The point isn't collecting these numbers—it's letting the model say "something's off" before the user feels it.
Sensor Data Sources
iOS: HealthKit
HealthKit—the only correct way to get health data on iOS. Direct sensor requests without HealthKit violate App Store guidelines.
import HealthKit
class HealthDataCollector {
private let healthStore = HKHealthStore()
func requestAuthorization() async throws {
let types: Set<HKQuantityType> = [
HKQuantityType(.heartRate),
HKQuantityType(.oxygenSaturation),
HKQuantityType(.stepCount),
HKQuantityType(.heartRateVariabilitySDNN),
HKQuantityType(.restingHeartRate)
]
try await healthStore.requestAuthorization(toShare: [], read: types)
}
func observeHeartRate(handler: @escaping (Double) -> Void) {
let heartRateType = HKQuantityType(.heartRate)
let query = HKAnchoredObjectQuery(
type: heartRateType,
predicate: nil,
anchor: nil,
limit: HKObjectQueryNoLimit
) { _, samples, _, _, _ in
guard let samples = samples as? [HKQuantitySample] else { return }
samples.forEach { sample in
let bpm = sample.quantity.doubleValue(
for: HKUnit(from: "count/min")
)
handler(bpm)
}
}
query.updateHandler = { _, samples, _, _, _ in
guard let samples = samples as? [HKQuantitySample] else { return }
samples.forEach { sample in
handler(sample.quantity.doubleValue(for: HKUnit(from: "count/min")))
}
}
healthStore.execute(query)
}
}
HKAnchoredObjectQuery—right choice for real-time observation. Standard HKSampleQuery takes snapshot and doesn't update.
Android: Health Connect + Direct Sensors
Health Connect (API 26+)—HealthKit analogue for Android. Aggregates data from Galaxy Health, Fitbit, Garmin. Direct sensor access via SensorManager:
class SensorCollector(private val context: Context) : SensorEventListener {
private val sensorManager = context.getSystemService(SensorManager::class.java)
private val heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE)
fun startMonitoring() {
sensorManager.registerListener(
this,
heartRateSensor,
SensorManager.SENSOR_DELAY_NORMAL
)
}
override fun onSensorChanged(event: SensorEvent) {
if (event.sensor.type == Sensor.TYPE_HEART_RATE) {
val bpm = event.values[0]
val accuracy = event.accuracy // SENSOR_STATUS_ACCURACY_HIGH required
if (accuracy >= SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM) {
processHeartRate(bpm)
}
}
}
}
Accuracy check mandatory. SENSOR_STATUS_UNRELIABLE (0) produces artifacts: 255 bpm on wet sensor.
AI Analysis: Anomaly Detection
Task—identify deviations from personal norm. Not from medical norms (not a medical device), but user-specific norm.
Isolation Forest—works well for multidimensional time series with small feature set. Train on "normal" behavior 2–4 weeks, identify outliers. Converts to CoreML via coremltools.converters.sklearn.
Rolling statistics + z-score—simpler, more interpretable, no ML:
func detectAnomaly(currentHR: Double, history: [Double]) -> AnomalyLevel {
let mean = history.reduce(0, +) / Double(history.count)
let variance = history.map { pow($0 - mean, 2) }.reduce(0, +) / Double(history.count)
let stdDev = sqrt(variance)
let zScore = abs(currentHR - mean) / stdDev
switch zScore {
case 0..<2.0: return .normal
case 2.0..<3.0: return .elevated
default: return .alert
}
}
z-score > 3—statistically significant anomaly. But need context: 160 bpm after WorkoutStart in HealthKit—normal, same rate at rest—anomaly. Activity context via CMMotionActivityManager (iOS) or ActivityRecognitionClient (Android).
Personalized Recommendations
Based on aggregated patterns (HRV, resting heart rate, steps, sleep quality) build recommendation system. Not "exercise more"—"your HRV dropped 18% over 3 days, usually correlates with poor sleep—light workout recommended today".
Implement as rule-based system on ML analytics: ML identifies pattern, rules convert it to specific message. Simpler to test and adjust than "black box".
Privacy and Regulations
Health data—sensitive. GDPR and Apple Review require explicit consent per data type. Server storage must be encrypted (AES-256 at rest, TLS 1.3 in transit).
If app positioned as medical (diagnosis, treatment)—FDA 510(k) clearance (USA) or CE marking (EU) needed. Wellness apps without medical claims—this regulation doesn't apply, but marketing must account for it.
Development Process
Design data pipeline: sources → normalization → storage. Develop anomaly detection ML model, train and validate. Convert to CoreML/TFLite. Integrate with HealthKit / Health Connect. UI components: health dashboard, alerts, recommendations. Test on real wearables.
Timeframe Estimates
Basic monitoring with z-score detection and dashboard—2–3 weeks. Full AI system with Isolation Forest, personalized recommendations, background model updates—4–8 weeks.







