core-motion
dpearson2699/swift-ios-skills
Access iOS device motion sensors: accelerometer, gyroscope, magnetometer, pedometer, activity recognition, altitude, and more.
What is core-motion?
Core Motion provides unified access to iOS device sensors including accelerometer, gyroscope, magnetometer, pedometer, activity recognition, altitude, and specialized sensors like AirPods head tracking and watchOS dive depth. Use this when building motion-based interactions, fitness tracking, activity detection, or sensor-driven features.
- Read raw accelerometer, gyroscope, and magnetometer data at configurable update intervals
- Access fused device motion with attitude (roll, pitch, yaw), user acceleration, and gravity vectors
- Count steps, measure distance, detect floors, and track pace/cadence via CMPedometer
- Recognize user activity (walking, running, cycling, driving, stationary) with confidence levels
- Query historical sensor and activity data over date ranges
- Support multiple attitude reference frames (arbitrary, corrected, magnetic north, true north)
How to install core-motion
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-motion- Add NSMotionUsageDescription to Info.plist with user-facing explanation
- Create exactly one CMMotionManager instance per app (multiple instances degrade sensor rates)
- Check authorization status for CMPedometer, CMMotionActivityManager, and CMAltimeter before use
- Verify sensor availability (isAccelerometerAvailable, isGyroAvailable, etc.) before starting updates
How to use core-motion
- 1.Import CoreMotion framework
- 2.Add NSMotionUsageDescription to Info.plist
- 3.Create a single CMMotionManager instance for your app
- 4.Check sensor availability and authorization status
- 5.Set appropriate update interval (e.g., 1.0/60.0 for 60 Hz)
- 6.Start updates with a handler block or polling pattern
- 7.Process sensor data in the callback or game loop
- 8.Call stop methods when done to conserve battery
Use cases
- Build tilt-based game controls or motion-responsive UI using accelerometer and gyroscope
- Implement step counters and distance tracking for fitness apps
- Detect when a user transitions between stationary, walking, running, or driving states
- Create compass or navigation features using magnetometer with corrected reference frames
- Track workout metrics (steps, floors, pace) in real-time or historical queries
- iOS game developers building motion-controlled gameplay
- Fitness and health app developers tracking steps and activity
- Navigation and mapping app developers
- Accessibility engineers building motion-based interactions
- Developers building AR experiences requiring device orientation
core-motion FAQ
Multiple instances degrade sensor update rates and waste battery. Create one per app and reuse it.
Handler-based updates call a closure on a queue for each sensor sample; polling retrieves the latest sample in your game loop. Polling is preferred for games; handlers suit background monitoring.
Use .xArbitraryZVertical or .xArbitraryCorrectedZVertical for games and simple tilt controls. For compass features, check availableAttitudeReferenceFrames() and fall back to an available frame if magnetic or true north is unavailable.
Raw accelerometer/gyro/device-motion have no explicit permission request, but you must include NSMotionUsageDescription in Info.plist. CMPedometer, CMMotionActivityManager, and CMAltimeter have authorizationStatus() checks.
Higher update intervals (e.g., 60 Hz) consume more battery. Use the lowest interval needed for your use case and stop updates when not in use.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: core-motion description: "Access Core Motion accelerometer, gyroscope, magnetometer, device-motion, pedometer, activity-recognition, altitude, headphone motion, batched high-frequency workout motion, and water-submersion/depth data. Use when reading device sensors, counting steps, detecting walking/running/driving/cycling, tracking altitude, building motion interactions, handling AirPods head tracking, or implementing watchOS dive/depth features."
CoreMotion
Read device motion, pedometer/activity, altitude, headphone, batched-workout, and submersion sensors with Core Motion. Scope: Swift 6.3, iOS 26+.
Contents
- Setup
- CMMotionManager: Sensor Data
- Processed Device Motion
- CMPedometer: Step and Distance Data
- CMMotionActivityManager: Activity Recognition
- CMAltimeter: Altitude Data
- Update Intervals and Battery
- Common Mistakes
- Review Checklist
- References
Setup
Info.plist
Add NSMotionUsageDescription to Info.plist with a user-facing string explaining
why your app needs motion data. Without this key, the app crashes on first access.
<key>NSMotionUsageDescription</key>
<string>This app uses motion data to track your activity.</string>
Authorization
Use the matching manager's authorizationStatus() or authorizationStatus
property when an API exposes one (CMPedometer, CMMotionActivityManager,
CMAltimeter, headphone motion, batched sensors, and submersion). Raw
CMMotionManager accelerometer/gyro/device-motion streams have no explicit
authorization request API; still ship the usage string and handle errors from
start/update callbacks.
import CoreMotion
let status = CMMotionActivityManager.authorizationStatus()
switch status {
case .notDetermined:
// Will prompt on first use
break
case .authorized:
break
case .restricted, .denied:
// Direct user to Settings
break
@unknown default:
break
}
CMMotionManager: Sensor Data
Create exactly one CMMotionManager per app. Multiple instances degrade
sensor update rates.
import CoreMotion
let motionManager = CMMotionManager()
Accelerometer Updates
guard motionManager.isAccelerometerAvailable else { return }
motionManager.accelerometerUpdateInterval = 1.0 / 60.0 // 60 Hz
motionManager.startAccelerometerUpdates(to: .main) { data, error in
guard let acceleration = data?.acceleration else { return }
print("x: \(acceleration.x), y: \(acceleration.y), z: \(acceleration.z)")
}
// When done:
motionManager.stopAccelerometerUpdates()
Gyroscope Updates
guard motionManager.isGyroAvailable else { return }
motionManager.gyroUpdateInterval = 1.0 / 60.0
motionManager.startGyroUpdates(to: .main) { data, error in
guard let rotationRate = data?.rotationRate else { return }
print("x: \(rotationRate.x), y: \(rotationRate.y), z: \(rotationRate.z)")
}
motionManager.stopGyroUpdates()
Polling Pattern (Games)
For games, start updates without a handler and poll the latest sample each frame:
motionManager.startAccelerometerUpdates()
// In your game loop / display link:
if let data = motionManager.accelerometerData {
let tilt = data.acceleration.x
// Move player based on tilt
}
Processed Device Motion
Device motion fuses accelerometer, gyroscope, and magnetometer into a single
CMDeviceMotion object with attitude, user acceleration (gravity removed),
rotation rate, and calibrated magnetic field.
When giving device-motion guidance, show the runtime frame check in the snippet
instead of hard-coding a corrected, magnetic-north, or true-north frame. Fall
back to .xArbitraryZVertical when the preferred frame is unavailable.
guard motionManager.isDeviceMotionAvailable else { return }
let availableFrames = CMMotionManager.availableAttitudeReferenceFrames()
let frame: CMAttitudeReferenceFrame = availableFrames.contains(.xArbitraryCorrectedZVertical)
? .xArbitraryCorrectedZVertical
: .xArbitraryZVertical
motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
motionManager.startDeviceMotionUpdates(
using: frame,
to: .main
) { motion, error in
guard let motion else { return }
let attitude = motion.attitude // roll, pitch, yaw
let userAccel = motion.userAcceleration
let gravity = motion.gravity
let heading = motion.heading // degrees relative to the current frame
print("Pitch: \(attitude.pitch), Roll: \(attitude.roll)")
}
motionManager.stopDeviceMotionUpdates()
Attitude Reference Frames
For simple tilt controls, use .xArbitraryZVertical or
.xArbitraryCorrectedZVertical; they avoid magnetometer/location dependencies.
Before requesting corrected, magnetic-north, or true-north frames, call
CMMotionManager.availableAttitudeReferenceFrames() and fall back to an
available frame.
| Frame | Use Case |
|---|---|
.xArbitraryZVertical | Default. Z is vertical, X arbitrary at start. Most games. |
.xArbitraryCorrectedZVertical | Same as above, corrected for gyro drift over time. |
.xMagneticNorthZVertical | X points to magnetic north. Requires magnetometer. |
.xTrueNorthZVertical | X points to true north. Requires magnetometer + location. |
Check available frames before use:
let available = CMMotionManager.availableAttitudeReferenceFrames()
if available.contains(.xTrueNorthZVertical) {
// Safe to use true north
}
CMPedometer: Step and Distance Data
CMPedometer provides step counts, distance, pace, cadence, and floor counts.
let pedometer = CMPedometer()
guard CMPedometer.isStepCountingAvailable() else { return }
// Historical query
pedometer.queryPedometerData(
from: Calendar.current.startOfDay(for: Date()),
to: Date()
) { data, error in
guard let data else { return }
print("Steps today: \(data.numberOfSteps)")
print("Distance: \(data.distance?.doubleValue ?? 0) meters")
print("Floors up: \(data.floorsAscended?.intValue ?? 0)")
}
// Live updates
pedometer.startUpdates(from: Date()) { data, error in
guard let data else { return }
print("Steps: \(data.numberOfSteps)")
}
// Stop when done
pedometer.stopUpdates()
Availability Checks
| Method | What It Checks |
|---|---|
isStepCountingAvailable() | Step counter hardware |
isDistanceAvailable() | Distance estimation |
isFloorCountingAvailable() | Barometric altimeter for floors |
isPaceAvailable() | Pace data |
isCadenceAvailable() | Cadence data |
CMMotionActivityManager: Activity Recognition
Detects whether the user is stationary, walking, running, cycling, or in a vehicle.
let activityManager = CMMotionActivityManager()
guard CMMotionActivityManager.isActivityAvailable() else { return }
// Live activity updates
activityManager.startActivityUpdates(to: .main) { activity in
guard let activity else { return }
if activity.walking {
print("Walking (confidence: \(activity.confidence.rawValue))")
} else if activity.running {
print("Running")
} else if activity.automotive {
print("In vehicle")
} else if activity.cycling {
print("Cycling")
} else if activity.stationary {
print("Stationary")
}
}
activityManager.stopActivityUpdates()
Historical Activity Query
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
activityManager.queryActivityStarting(
from: yesterday,
to: Date(),
to: .main
) { activities, error in
guard let activities else { return }
for activity in activities {
print("\(activity.startDate): walking=\(activity.walking)")
}
}
CMAltimeter: Altitude Data
Altimeter access is covered by NSMotionUsageDescription; handle denied motion
access through unavailable data and update-handler errors.
let altimeter = CMAltimeter()
guard CMAltimeter.isRelativeAltitudeAvailable() else { return }
altimeter.startRelativeAltitudeUpdates(to: .main) { data, error in
guard let data else { return }
print("Relative altitude: \(data.relativeAltitude) meters")
print("Pressure: \(data.pressure) kPa")
}
altimeter.stopRelativeAltitudeUpdates()
Absolute altitude is altitude relative to sea level, not GPS-based altitude. First check availability. Absolute altitude is available only on supported hardware such as iPhone 12 or later and Apple Watch Series 6, Apple Watch SE, or later.
guard CMAltimeter.isAbsoluteAltitudeAvailable() else { return }
altimeter.startAbsoluteAltitudeUpdates(to: .main) { data, error in
guard let data else { return }
print("Altitude: \(data.altitude)m, accuracy: \(data.accuracy)m")
}
altimeter.stopAbsoluteAltitudeUpdates()
Update Intervals and Battery
| Interval | Hz | Use Case | Battery Impact |
|---|---|---|---|
1.0 / 10.0 | 10 | UI orientation | Low |
1.0 / 30.0 | 30 | Casual games | Moderate |
1.0 / 60.0 | 60 | Action games | High |
1.0 / 100.0 | 100 | Max rate (iPhone) | Very High |
Use the lowest frequency that meets your needs. Do not assume a fixed maximum
sample rate across devices. For high-frequency workout motion, use
CMBatchedSensorManager where supported and read its reported
accelerometerDataFrequency or deviceMotionDataFrequency instead of assigning
those read-only properties.
Common Mistakes
DON'T: Create multiple CMMotionManager instances
Retain one app-level CMMotionManager; competing instances can reduce update
rates.
DON'T: Skip sensor availability checks
Apply the matching is...Available gate immediately before starting each
sensor stream.
DON'T: Forget to stop updates
Pair every start with the matching stop in the counterpart lifecycle or task cancellation path.
DON'T: Use unnecessarily high update rates
Choose the lowest rate that meets the interaction and use the Update Intervals and Battery table as a starting point.
DON'T: Assume all CMMotionActivity properties are mutually exclusive
// WRONG -- checking only one property
if activity.walking { handleWalking() }
// CORRECT -- multiple can be true simultaneously; check confidence
if activity.walking && activity.confidence == .high {
handleWalking()
} else if activity.automotive && activity.confidence != .low {
handleDriving()
}
Review Checklist
-
NSMotionUsageDescriptionpresent in Info.plist with a clear explanation - Single
CMMotionManagerinstance shared across the app - Sensor availability checked before starting updates (
isAccelerometerAvailable, etc.) - Authorization status checked before pedometer/activity APIs
- Update interval set to the lowest acceptable frequency
- All
start*Updatescalls have matchingstop*Updatesin lifecycle counterparts - Handlers dispatched to appropriate queues (not blocking main for heavy processing)
-
CMMotionActivity.confidencechecked before acting on activity type - Error parameters checked in update handlers
- Device-motion snippets call
CMMotionManager.availableAttitudeReferenceFrames()before requesting a specific attitude frame - Attitude reference frame chosen based on actual need (not defaulting to true north unnecessarily)
References
- Extended patterns (SwiftUI integration, batched sensor manager, headphone motion, water submersion): references/motion-patterns.md
- CoreMotion framework
- CMMotionManager
- CMPedometer
- CMMotionActivityManager
- CMDeviceMotion
- CMAltimeter
- CMAbsoluteAltitudeData
- CMBatchedSensorManager
- CMHeadphoneMotionManager
- CMWaterSubmersionManager
- Accessing submersion data
- Getting processed device-motion data
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

core-nfc
Read and write NFC tags on iPhone using CoreNFC framework.

coreml
Load, configure, and run Core ML models in iOS apps for on-device machine learning inference.

cryptokit
Apple CryptoKit for Swift cryptographic primitives: hashing, HMAC, AES-GCM, signing, key agreement, and post-quantum operations.

cryptotokenkit
Access security tokens and smart cards via CryptoTokenKit for token drivers, NFC sessions, and certificate-based authentication.

debugging-instruments
Debug iOS crashes, memory leaks, hangs, and performance using LLDB, Memory Graph Debugger, and Instruments.

device-integrity
Verify device legitimacy and app integrity using Apple's DeviceCheck and App Attest.