How do you detect which sensors and health data exist at runtime, and what does the simulator report?
Predict first
What does the iOS Simulator report?
import CoreMotion
import HealthKit
let mm = CMMotionManager()
print("accelerometer:", mm.isAccelerometerAvailable, "gyro:", mm.isGyroAvailable, "device motion:", mm.isDeviceMotionAvailable, "magnetometer:", mm.isMagnetometerAvailable)
print("pedometer:", CMPedometer.isStepCountingAvailable(), "distance:", CMPedometer.isDistanceAvailable(), "altimeter:", CMAltimeter.isRelativeAltitudeAvailable(), "activity:", CMMotionActivityManager.isActivityAvailable())
print("health data available:", HKHealthStore.isHealthDataAvailable())
- All motion sensors unavailable but health data available
- All sensors available
- Health data unavailable
Mental model. Checking availability is looking for the instrument before you try to play it.
Every sensor API has a class or instance availability check: CMMotionManager.isAccelerometerAvailable, isGyroAvailable, isDeviceMotionAvailable, CMPedometer.isStepCountingAvailable(), CMAltimeter.isRelativeAltitudeAvailable(), CMMotionActivityManager.isActivityAvailable(), and HKHealthStore.isHealthDataAvailable(). Hardware differs (iPads and old phones lack parts, the simulator has none), so check before you start updates and design a fallback. In the iOS Simulator run, every motion check printed false, while isHealthDataAvailable() was true, so a health feature can run in the simulator with no data while a motion feature cannot run at all, and you need a device (or recorded data and an abstraction) to test it.
Wrap sensors behind a protocol so tests can inject samples, ask for permission in context (motion and fitness data has its own prompt), stop updates when the screen goes away, and set a sensible update interval (the default 0.01 s is rarely needed). The values came from a simulator process; a device’s answers were not run.
The simulator has no motion hardware.
Common traps
- Starting motion updates without checking. On unsupported hardware nothing arrives.
- Assuming the simulator behaves like a phone. Motion sensors are absent.
They might follow up with
- How do I test motion code? Hide the manager behind a protocol and feed recorded samples.
Related questions
- 17.3.2 How does HealthKit handle authorization and units, and what should an app know about Core Motion and sensor…
- 17.10.3 How do HealthKit units and aggregation styles work, and why does converting mg/dL to mmol/L crash?
← How do HealthKit units and aggregation styles work, and why does…