PluginBench
Skill
Pass
Audit score 90

core-motion

dpearson2699/swift-ios-skills

How to install core-motion

npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-motion
Claude Code
Cursor
Windsurf
Cline
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 sensor data -- accelerometer, gyroscope, magnetometer, pedometer, activity recognition, altitude, headphone motion, batched motion, and submersion depth -- on iOS and watchOS. CoreMotion fuses raw sensor inputs into processed device-motion data and provides pedometer/activity APIs for fitness and navigation use cases. Targets 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.

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

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:

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

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.

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

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

// WRONG -- degrades update rates for all instances
class ViewA { let motion = CMMotionManager() }
class ViewB { let motion = CMMotionManager() }

// CORRECT -- single instance, shared across the app
@Observable
final class MotionService {
    static let shared = MotionService()
    let manager = CMMotionManager()
}

DON'T: Skip sensor availability checks

// WRONG -- crashes on devices without gyroscope
motionManager.startGyroUpdates(to: .main) { data, _ in }

// CORRECT -- check first
guard motionManager.isGyroAvailable else {
    showUnsupportedMessage()
    return
}
motionManager.startGyroUpdates(to: .main) { data, _ in }

DON'T: Forget to stop updates

// WRONG -- updates keep running, draining battery
class MotionVC: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        motionManager.startAccelerometerUpdates(to: .main) { _, _ in }
    }
    // Missing viewDidDisappear stop!
}

// CORRECT -- stop in the counterpart lifecycle method
override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    motionManager.stopAccelerometerUpdates()
}

DON'T: Use unnecessarily high update rates

// WRONG -- 100 Hz for a compass display
motionManager.deviceMotionUpdateInterval = 1.0 / 100.0

// CORRECT -- 10 Hz is more than enough for a compass
motionManager.deviceMotionUpdateInterval = 1.0 / 10.0

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

  • 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

Related skills

More from dpearson2699/swift-ios-skills and the wider catalog.

SW

swiftui-animation

dpearson2699/swift-ios-skills

Implement, review, or improve SwiftUI animations and transitions. Use when adding explicit animations with withAnimation, configuring implicit animations with .animation(_:body:) or .animation(_:value:), configuring spring animations (.smooth, .snappy, .bouncy), building phase or keyframe animations with PhaseAnimator/KeyframeAnimator, creating hero transitions with matchedGeometryEffect or matchedTransitionSource, adding SF Symbol effects (iOS 17 bounce, pulse, variableColor, scale, appear, disappear, replace; iOS 18 breathe, rotate, wiggle), implementing custom Transition or CustomAnimation types, or ensuring animations respect accessibilityReduceMotion.

3.0k installsAudited
IO

ios-accessibility

dpearson2699/swift-ios-skills

Implements, reviews, or improves accessibility in iOS/macOS apps with SwiftUI, UIKit, and AppKit. Use when adding VoiceOver, Voice Control, Switch Control, or Full Keyboard Access support; when working with accessibility labels, hints, values, traits, accessibilityInputLabels, NSAccessibility, grouping, reading order, accessibility focus restoration with @AccessibilityFocusState, Dynamic Type, @ScaledMetric, custom rotors, accessibility actions, XCTest accessibility checks, App Store Accessibility Nutrition Labels, App Store Connect accessibility answers, a11y compliance audits, or system accessibility preferences.

2.7k installsAudited
SW

swiftui-patterns

dpearson2699/swift-ios-skills

Builds and reviews SwiftUI views with modern MV architecture, state management, view composition, and migration/availability guidance. Covers @Observable ownership rules, @State/@Bindable/@Environment wiring, view decomposition, custom ViewModifiers, environment values, async data loading with .task, iOS 26+ handoff reminders, Writing Tools, clipboard availability caveats, and performance guidelines. Use when structuring SwiftUI app state, managing @Observable, composing view hierarchies, or correcting SwiftUI pattern guidance.

2.6k installsAudited
SW

swiftui-performance

dpearson2699/swift-ios-skills

Audit and improve SwiftUI runtime performance. Use when diagnosing slow rendering, janky scrolling, high CPU, memory usage, excessive view updates, layout thrash, body evaluation cost, identity churn, view lifetime issues, lazy loading, Instruments profiling guidance, and performance audit requests.

2.6k installsAudited
AP

app-store-review

dpearson2699/swift-ios-skills

Prepare for App Store review and prevent rejections. Covers App Store review guidelines, app rejection reasons, PrivacyInfo.xcprivacy privacy manifest requirements, required API reason codes, in-app purchase IAP and StoreKit rules, App Store Guidelines compliance, ATT App Tracking Transparency, EU DMA Digital Markets Act, HIG compliance checklist, app submission preparation, review preparation, metadata requirements, entitlements, widgets, and Live Activities review rules. Use when preparing for App Store submission, fixing rejection reasons, auditing privacy manifests, implementing ATT consent flow, configuring StoreKit IAP, or checking HIG compliance.

2.5k installs
IO

ios-networking

dpearson2699/swift-ios-skills

Build, review, or improve networking code in iOS/macOS apps using URLSession with async/await, structured concurrency, and modern Swift patterns. Use when working with REST APIs, downloading files, uploading data, WebSocket connections, pagination, retry logic, request middleware, caching, background transfers, or network reachability monitoring. Also use when handling HTTP requests, API clients, network error handling, or data fetching in Swift apps.

2.5k installs