Core Motion

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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.

AI 產生的概覽

指導 Swift 開發者讀取 Apple Core Motion 感測器資料,包括加速度計、陀螺儀、計步器、活動辨識與高度。

功能
此技能為在 iOS 26 及更新版本、Swift 6.3 中使用 Apple Core Motion 框架提供參考指引與程式碼片段。內容涵蓋設定需求、授權、CMMotionManager 感測器串流、處理後的裝置運動、CMPedometer、CMMotionActivityManager、CMAltimeter、更新間隔、常見錯誤與審查清單。它產出的是說明性文件,而非可執行程式碼。
適用情境
適用於實作或審查讀取裝置感測器、計步、偵測步行或駕駛、追蹤高度,或處理耳機與入水運動的 iOS/watchOS 功能。面向需要使用 Core Motion API 並尋求設定、授權與最佳實務指引的開發者。
執行需求
除 AI 代理外,無需指令碼或執行階段相依性。指引面向 Swift 6.3 與 iOS 26+,並提及 Info.plist 設定與裝置感測器可用性。

CoreMotion

Read device motion, pedometer/activity, altitude, headphone, batched-workout, and submersion sensors with Core Motion. Scope: Swift 6.3, iOS 26+.

Contents

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.

xml
<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.

swift
import CoreMotion
let status = CMMotionActivityManager.authorizationStatus()switch status {case .notDetermined:    // Will prompt on first use    breakcase .authorized:    breakcase .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.

swift
import CoreMotion
let motionManager = CMMotionManager()

Accelerometer Updates

swift
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

swift
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:

swift
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.

swift
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.

FrameUse Case
.xArbitraryZVerticalDefault. Z is vertical, X arbitrary at start. Most games.
.xArbitraryCorrectedZVerticalSame as above, corrected for gyro drift over time.
.xMagneticNorthZVerticalX points to magnetic north. Requires magnetometer.
.xTrueNorthZVerticalX points to true north. Requires magnetometer + location.

Check available frames before use:

swift
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.

swift
let pedometer = CMPedometer()
guard CMPedometer.isStepCountingAvailable() else { return }
// Historical querypedometer.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 updatespedometer.startUpdates(from: Date()) { data, error in    guard let data else { return }    print("Steps: \(data.numberOfSteps)")}
// Stop when donepedometer.stopUpdates()

Availability Checks

MethodWhat 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.

swift
let activityManager = CMMotionActivityManager()
guard CMMotionActivityManager.isActivityAvailable() else { return }
// Live activity updatesactivityManager.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

swift
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.

swift
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.

swift
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

IntervalHzUse CaseBattery Impact
1.0 / 10.010UI orientationLow
1.0 / 30.030Casual gamesModerate
1.0 / 60.060Action gamesHigh
1.0 / 100.0100Max 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

swift
// WRONG -- checking only one propertyif activity.walking { handleWalking() }
// CORRECT -- multiple can be true simultaneously; check confidenceif activity.walking && activity.confidence == .high {    handleWalking()} else if activity.automotive && activity.confidence != .low {    handleDriving()}

Review Checklist

  • NSMotionUsageDescription present in Info.plist with a clear explanation
  • Single CMMotionManager instance 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*Updates calls have matching stop*Updates in lifecycle counterparts
  • Handlers dispatched to appropriate queues (not blocking main for heavy processing)
  • CMMotionActivity.confidence checked 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

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/core-motion提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新