mcpField
A
apple-corelocation

apple-corelocation

github.com/ios-agentDevelopment1255 installsUpdated 34w ago
Repository

About apple-corelocation

apple-corelocation is a programming reference skill for developers using CoreLocation on Apple platforms. It covers location updates, permissions, geofencing, geocoding, and background updates, including async APIs available in iOS 17+.

Key features

  1. 01Shows iOS 17+ async location patterns
  2. 02Explains authorization and permission setup
  3. 03Covers region monitoring and geocoding
  4. 04Describes background location and power use
  5. 05Lists common CoreLocation APIs

Use cases

  1. 01Implement live location in a SwiftUI app
  2. 02Handle location permissions and status changes
  3. 03Set up geofences or address conversion
  4. 04Reduce power use for background updates

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/ios-agent/iosagent.dev --skill apple-corelocation

After installing, type/apple-corelocationin Claude Code to confirm it loaded.

Bundled files

References and scripts installed along with SKILL.md.

references/
authorization.md
background.md
beacon-compass.md
geocoding.md
live-updates.md
location-manager.md
monitoring.md

Details

From the project README

Apple CoreLocation Skill

Use this skill to write correct, modern CoreLocation code. CoreLocation provides services for geographic location, altitude, orientation, and proximity to iBeacons. It uses Wi-Fi, GPS, Bluetooth, magnetometer, barometer, and cellular hardware.

When to Read Reference Files

This SKILL.md contains the essential patterns and quick-reference API surface. For deeper implementation details, read the appropriate reference file:

TopicReference FileWhen to Read
Live Updates & async/await patternsreferences/live-updates.mdSwiftUI apps, async location streams, background activity sessions
Authorization & Permissionsreferences/authorization.mdPermission flows, Info.plist keys, authorization status handling
Region Monitoring & CLMonitorreferences/monitoring.mdGeofencing, condition monitoring, circular regions
Geocodingreferences/geocoding.mdAddress ↔ coordinate conversion, reverse geocoding, CLPlacemark
iBeacon & Compassreferences/beacon-compass.mdBeacon ranging, heading updates, magnetometer
Background Locationreferences/background.mdBackground updates, CLBackgroundActivitySession, power optimization
CLLocationManager APIreferences/location-manager.mdFull property/method reference for CLLocationManager

Modern CoreLocation (iOS 17+): Prefer Async/Await

Since iOS 17, CoreLocation supports Swift concurrency. Prefer the modern async API over the legacy delegate-based approach for new projects.

Getting Live Location Updates (Recommended Pattern)
import CoreLocation

let updates = CLLocationUpdate.liveUpdates()

for try await update in updates {
    if let location = update.location {
        // Process location
        print("Lat: \(location.coordinate.latitude), Lon: \(location.coordinate.longitude)")
    }
    if update.authorizationDenied {
        // Handle denied authorization
    }
    if update.authorizationRequestInProgress {
        // System is showing the authorization dialog
    }
}

The system automatically prompts for authorization when iteration begins if status is .notDetermined. No explicit requestWhenInUseAuthorization() call is needed with this pattern, but you may still call it for controlled timing.

Live Updates with Accuracy Configuration
// High accuracy (GPS, more power)
let updates = CLLocationUpdate.liveUpdates(.default)

// Power-efficient options
let updates = CLLocationUpdate.liveUpdates(.automotiveNavigation)
let updates = CLLocationUpdate.liveUpdates(.otherNavigation)
let updates = CLLocationUpdate.liveUpdates(.fitness)
let updates = CLLocationUpdate.liveUpdates(.airborne)
CLLocationUpdate Properties
  • location: CLLocation? — The location, or nil if unavailable
  • isStationary: Bool — Whether the device is stationary
  • authorizationDenied: Bool — Authorization was denied
  • authorizationDeniedGlobally: Bool — Location services disabled system-wide
  • authorizationRequestInProgress: Bool — Auth dialog is being shown
  • insufficientlyInUse: Bool — App lacks sufficient "in use" state
  • locationUnavailable: Bool — Location data temporarily unavailable
  • accuracyLimited: Bool — Accuracy authorization is reduced

SwiftUI Integration Pattern

@MainActor
class LocationsHandler: ObservableObject {
    static let shared = LocationsHandler()
    private let manager: CLLocationManager
    private var background: CLBackgroundActivitySession?

    @Published var lastLocation = CLLocation()
    @Published var isStationary = false

    @Published var updatesStarted: Bool = UserDefaults.standard.bool(forKey: "liveUpdatesStarted") {
        didSet { UserDefaults.standard.set(updatesStarted, forKey: "liveUpdatesStarted") }
    }

    private init() {
        self.manager = CLLocationManager()
    }

    func startLocationUpdates() {
        if self.manager.authorizationStatus == .notDetermined {
            self.manager.requestWhenInUseAuthorization()
        }
        Task {
            do {
                self.updatesStarted = true
                let updates = CLLocationUpdate.liveUpdates()
                for try await update in updates {
                    if !self.updatesStarted { break }
                    if let loc = update.location {
                        self.lastLocation = loc
                        self.isStationary = update.isStationary
                    }
                }
            } catch {
                print("Could not start location updates")
            }
        }
    }

    func stopLocationUpdates() {
        self.updatesStarted = false
    }
}

Authorization Quick Reference

Info.plist Keys (Required)
KeyWhen to Use
NSLocationWhenInUseUsageDescriptionApp uses location while in foreground
NSLocationAlwaysAndWhenInUseUsageDescriptionApp needs location in background too
NSLocationDefaultAccuracyReducedRequest reduced accuracy by default
Authorization Status Values (CLAuthorizationStatus)
ValueMeaning
.notDeterminedUser hasn't been asked yet
.restrictedApp cannot use location (e.g., parental controls)
.deniedUser explicitly denied
.authorizedWhenInUseApp can use location while in foreground
.authorizedAlwaysApp can use location at any time
Requesting Authorization
let manager = CLLocationManager()

// For foreground-only access
manager.requestWhenInUseAuthorization()

// For background access (after getting "When In Use" first)
manager.requestAlwaysAuthorization()

// For temporary full accuracy (when user granted reduced accuracy)
manager.requestTemporaryFullAccuracyAuthorization(withPurposeKey: "MyPurposeKey")

Condition Monitoring with CLMonitor (iOS 17+)

let monitor = await CLMonitor("myMonitor")

// Add a circular geographic condition
await monitor.add(
    CLMonitor.CircularGeographicCondition(center: coordinate, radius: 200),
    identifier: "coffee-shop"
)

// Observe events
for try await event in await monitor.events {
    switch event.state {
    case .satisfied:
        print("Entered region: \(event.identifier)")
    case .unsatisfied:
        print("Exited region: \(event.identifier)")
    default:
        break
    }
}

Geocoding Quick Reference

let geocoder = CLGeocoder()

// Reverse geocode: coordinate → address
geocoder.reverseGeocodeLocation(location) { placemarks, error in
    if let placemark = placemarks?.first {
        print(placemark.locality ?? "Unknown city")
    }
}

// Forward geocode: address → coordinate
geocoder.geocodeAddressString("1 Apple Park Way, Cupertino") { placemarks, error in
    if let location = placemarks?.first?.location {
        print(location.coordinate)
    }
}

CLLocation Key Properties

PropertyTypeDescription
coordinateCLLocationCoordinate2DLatitude and longitude (WGS 84)
altitudeCLLocationDistanceMeters above sea level
horizontalAccuracyCLLocationAccuracyAccuracy in meters (negative = invalid)
verticalAccuracyCLLocationAccuracyAltitude accuracy in meters
speedCLLocationSpeedMeters per second
courseCLLocationDirectionDegrees relative to true north
timestampDateWhen the location was determined
floorCLFloor?Floor of a building, if available
sourceInformationCLLocationSourceInformation?Info about the location source

Power Optimization Guidelines

Choose the most power-efficient service for your use case:

  1. Visits service (startMonitoringVisits()) — Most power-efficient. Reports places visited and time spent. Good for: check-in apps, travel logs.

  2. Significant-change service (startMonitoringSignificantLocationChanges()) — Low power, uses Wi-Fi/cellular only. Good for: approximate location tracking.

  3. Standard location service (startUpdatingLocation()) — Configurable accuracy via desiredAccuracy. Good for: navigation, fitness tracking.

  4. Live updates (CLLocationUpdate.liveUpdates()) — Modern async API with configurable activity types. Good for: any new project on iOS 17+.

Desired Accuracy Constants
ConstantDescription
kCLLocationAccuracyBestForNavigationHighest precision, most power
kCLLocationAccuracyBestBest available accuracy
kCLLocationAccuracyNearestTenMetersWithin ~10 meters
kCLLocationAccuracyHundredMetersWithin ~100 meters
kCLLocationAccuracyKilometerWithin ~1 km
kCLLocationAccuracyThreeKilometersWithin ~3 km
kCLLocationAccuracyReducedDeliberately reduced accuracy

Platform Considerations

  • visionOS: Location services are limited. Background updates are not supported. Region monitoring methods do nothing for compatible iPad/iPhone apps running in visionOS.
  • macOS: Apps are not suspended in background, so no special background capability needed.
  • watchOS: Supports background location with capability. Use CLBackgroundActivitySession.
  • Widgets: Check isAuthorizedForWidgetUpdates for widget eligibility.

Common Pitfalls

  • Always check horizontalAccuracy — negative values mean the coordinate is invalid.
  • Do not assume location is immediately available after starting services.
  • Handle authorization changes gracefully; users can revoke at any time via Settings.
  • Geocoder requests are rate-limited; cache results and do not geocode on every location update.
  • The system can pause location updates automatically. Set pausesLocationUpdatesAutomatically and activityType to help CoreLocation make good decisions.
  • For background updates on iOS: add the "Location updates" background mode capability AND set allowsBackgroundLocationUpdates = true on the location manager.

Comments

Markdown supported