Sample CodeiOS, iPadOSReviewed 2026-11-01View on Apple Developer

Tracking geographic locations in AR

At a glance

Item Summary
Purpose Run an ARGeoTrackingConfiguration, let a person place ARGeoAnchors by tapping the AR view or a map, show each anchor in RealityKit and MapKit, and save or load anchors as GPX files.
App architecture A storyboard UIKit app with one ViewController that owns the ARView session setup, a CLLocationManager, and the map. Separate extensions add coaching, GPX load/save, and helpers. GPXParser and GPXExporter handle the file format.
Main patterns Delegate callbacks throughout: ARSessionDelegate, CLLocationManagerDelegate, MKMapViewDelegate, ARCoachingOverlayViewDelegate, and the app’s own GPXParserDelegate.
Project style One target. ViewController is split across ViewController.swift, ViewController+CoachingOverlay.swift, ViewController+LoadSaveAnchors.swift, and a ViewController extension in Utilities.swift.
Execution model UIKit and framework callbacks. UI work from callbacks is submitted to DispatchQueue.main, and placemark entities are added after a distance-based asyncAfter delay.
State/event model ViewController stores the list of added geo anchors and their map overlays. Framework delegate callbacks drive all updates. No observation or publisher mechanism is used.
Key frameworks/packages ARKit, RealityKit, MapKit, UIKit, Photos (imported in ViewController.swift). The project declares no Swift package.

Project structure

GeoTrackingExample.xcodeproj/
GeoTrackingExample/
├── AppDelegate.swift                      device-support check, open-URL handler, scene configuration
├── SceneDelegate.swift                    window scene lifecycle (empty hooks)
├── ViewController.swift                   session, location, map, taps, ARSession/MapKit delegates
├── ViewController+CoachingOverlay.swift   ARCoachingOverlayViewDelegate, .geoTracking goal
├── ViewController+LoadSaveAnchors.swift   GPXParserDelegate; list, save, share, parse GPX
├── GPXParser.swift                        XMLParser-based GPX → [ARGeoAnchor]
├── GPXExporter.swift                      [ARGeoAnchor] → GPX string
├── GeoAnchorWithAssociatedData.swift      pairs an anchor with its map overlay
├── Utilities.swift                        AnchorIndicator, RealityKit placemark, alert/toast helpers
└── Info.plist                             GPX document type, scene manifest

Structure observations

  • The view controller is decomposed by feature into extensions, not into separate objects (GeoTrackingExample/ViewController+CoachingOverlay.swift:16, GeoTrackingExample/ViewController+LoadSaveAnchors.swift:17, GeoTrackingExample/Utilities.swift:79).
  • GPX handling is the only part split into standalone types, GPXParser and GPXExporter. Neither depends on the view controller (GeoTrackingExample/GPXParser.swift:14, GeoTrackingExample/GPXExporter.swift:10).
  • Info.plist declares a GPX document type (GeoTrackingExample/Info.plist:7) and a scene manifest that names SceneDelegate (GeoTrackingExample/Info.plist:44).

Overall architecture

Reference code

GeoTrackingExample/ViewController.swift:46 — viewDidLoad wires every collaborator to the controller

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set this view controller as the session's delegate.
        arView.session.delegate = self
        
        // Enable coaching.
        setupCoachingOverlay()
        
        // Set this view controller as the Core Location manager delegate.
        locationManager.delegate = self
        
        // Set this view controller as the MKMapView delegate.
        mapView.delegate = self
        
        // Disable automatic configuration and set up geotracking
        arView.automaticallyConfigureSession = false
                
        // Run a new AR Session.
        restartSession()
                
        // Add tap gesture recognizers
        arView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapOnARView(_:))))
        mapView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapOnMapView(_:))))
    }

Interpretation

Observed: ViewController is the delegate for the AR session, the location manager, the map view, the coaching overlay, and the GPX parser. Each callback updates views it owns directly.

Inference: this is a single-screen sample, so one controller acting as the hub keeps every framework interaction in one place. The extensions keep that hub readable without adding new object boundaries.

Ownership and state

Ownership evidence

GeoTrackingExample/ViewController.swift:243 — an added anchor is paired with its map overlay and recorded

    func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
        for geoAnchor in anchors.compactMap({ $0 as? ARGeoAnchor }) {
            // Effect a spatial-based delay to avoid blocking the main thread.
            DispatchQueue.main.asyncAfter(deadline: .now() + (distanceFromDevice(geoAnchor.coordinate) / 10)) {
                // Add an AR placemark visualization for the geo anchor.
                self.arView.scene.addAnchor(Entity.placemarkEntity(for: geoAnchor))
            }
            // Add a visualization for the geo anchor in the map view.
            let anchorIndicator = AnchorIndicator(center: geoAnchor.coordinate)
            self.mapView.addOverlay(anchorIndicator)

            // Remember the geo anchor we just added
            let anchorInfo = GeoAnchorWithAssociatedData(geoAnchor: geoAnchor, mapOverlay: anchorIndicator)
            self.geoAnchors.append(anchorInfo)
        }
    }
Owner Object or state Relationship Mutation authority
Storyboard ARView, MKMapView, labels, buttons Outlets (GeoTrackingExample/ViewController.swift:16, GeoTrackingExample/ViewController.swift:17) ViewController configures them
ViewController CLLocationManager, ARCoachingOverlayView Created as let properties (GeoTrackingExample/ViewController.swift:23, GeoTrackingExample/ViewController.swift:25) ViewController
ViewController geoAnchors: [GeoAnchorWithAssociatedData] Appended in session(_:didAdd:), popped in undoButtonTapped, cleared in restartSession() (GeoTrackingExample/ViewController.swift:32, GeoTrackingExample/ViewController.swift:129, GeoTrackingExample/ViewController.swift:182) ViewController
ARSession All anchors Anchors are added through session.add(anchor:) only after geotracking is localized (GeoTrackingExample/ViewController.swift:220, GeoTrackingExample/ViewController.swift:224) The session; the controller reads currentFrame?.anchors
GPXParser Parse state and anchorsFoundInFile private var (GeoTrackingExample/GPXParser.swift:19, GeoTrackingExample/GPXParser.swift:27) Only the parser
GPXExporter Template strings static let shared with private let templates (GeoTrackingExample/GPXExporter.swift:12) Immutable

Observed: the controller does not add visualizations when it creates an anchor. It adds the anchor to the session, then reacts in session(_:didAdd:). Anchors from taps and from GPX files therefore share one visualization path.

Scene lifecycle boundary

AppDelegate declares var window: UIWindow? and uses window?.rootViewController both to show an unsupported-device screen and to route opened GPX URLs to ViewController (GeoTrackingExample/AppDelegate.swift:21, GeoTrackingExample/AppDelegate.swift:27). The app also adopts the scene lifecycle: Info.plist names SceneDelegate, which declares its own window (GeoTrackingExample/SceneDelegate.swift:12) and has no URL-handling method. No source line assigns AppDelegate.window. Inference: with a scene manifest, the storyboard window belongs to the scene delegate, so the two AppDelegate paths may find no window. The source does not establish that they run.

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Staggered placemarks DispatchQueue.main.asyncAfter(deadline: .now() + distance / 10) Placemark entities are added later for farther anchors; the source comment says this avoids blocking the main thread GeoTrackingExample/ViewController.swift:246
Error alert DispatchQueue.main.async in session(_:didFailWithError:) Alert presentation is submitted to the main queue GeoTrackingExample/ViewController.swift:269
Alert and toast helpers DispatchQueue.main.async Every alert and toast is submitted to the main queue, whatever the caller GeoTrackingExample/Utilities.swift:81, GeoTrackingExample/Utilities.swift:93
Toast expiry DispatchQueue.main.asyncAfter plus a tag counter A later toast increments the tag, so an earlier timer does not hide it GeoTrackingExample/Utilities.swift:99, GeoTrackingExample/Utilities.swift:103
Delayed animation Entity.move(by:scale:after:duration:) uses asyncAfter The placemark rises 0.5 s after creation GeoTrackingExample/Utilities.swift:45, GeoTrackingExample/Utilities.swift:63
Async framework callbacks checkAvailability { ... }, getGeoLocation(forPoint:) { ... } Results arrive in closures; any alert they raise goes through the main-queue alertUser helper GeoTrackingExample/ViewController.swift:165, GeoTrackingExample/ViewController.swift:196
Synchronous parsing GPXParser.parse() calls XMLParser.parse() Parsing runs on the caller’s thread; the delegate fires from parserDidEndDocument GeoTrackingExample/GPXParser.swift:38, GeoTrackingExample/GPXParser.swift:79

Reference code

GeoTrackingExample/Utilities.swift:92 — main-queue toast with stale-timer protection

    func showToast(_ message: String, duration: TimeInterval = 2) {
        DispatchQueue.main.async {
            self.toastLabel.numberOfLines = message.components(separatedBy: "\n").count
            self.toastLabel.text = message
            self.toastLabel.isHidden = false
            
            // use tag to tell if label has been updated
            let tag = self.toastLabel.tag + 1
            self.toastLabel.tag = tag
            
            if duration > 0 {
                DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
                    // Do not hide if showToast is called again, before this block kicks in.
                    if self.toastLabel.tag == tag {
                        self.toastLabel.isHidden = true
                    }
                }
            }
        }
    }

Not established by source: which thread delivers ARSessionDelegate, checkAvailability, or getGeoLocation callbacks. geoAnchors is mutated in session(_:didAdd:) without a queue hop, and no lock or actor protects it.

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
Localization state session(_:didChange: ARGeoTrackingStatus) Updates the tracking label and hides controls until localized GeoTrackingExample/ViewController.swift:281
Localization gate isGeoTrackingLocalized reads currentFrame?.geoTrackingStatus Blocks anchor creation until .localized GeoTrackingExample/ViewController.swift:227
Map camera locationManager(_:didUpdateLocations:) Centers the map on the latest location GeoTrackingExample/ViewController.swift:308
Map overlay rendering mapView(_:rendererFor:) Draws AnchorIndicator circles GeoTrackingExample/ViewController.swift:322
Coaching ARCoachingOverlayView with .geoTracking goal Disables map and undo while coaching GeoTrackingExample/ViewController+CoachingOverlay.swift:38, GeoTrackingExample/ViewController+CoachingOverlay.swift:18
File import GPXParserDelegate.parser(_:didFinishParsingFileWithAnchors:) Parsed anchors enter the same addGeoAnchor(_:) path as taps GeoTrackingExample/ViewController+LoadSaveAnchors.swift:123
Framework import ARKit, RealityKit, MapKit Session and anchors, placemark entities, map and overlays GeoTrackingExample/ViewController.swift:10, GeoTrackingExample/ViewController.swift:9, GeoTrackingExample/ViewController.swift:11
Framework import Photos Imported in ViewController.swift; no Photos API call appears in the cited files GeoTrackingExample/ViewController.swift:12

Platform boundary

The deployment target is iOS 15.0 (GeoTrackingExample.xcodeproj/project.pbxproj:280). AppDelegate checks ARGeoTrackingConfiguration.isSupported at launch (GeoTrackingExample/AppDelegate.swift:19), and restartSession() checks location-based availability before running the session (GeoTrackingExample/ViewController.swift:165).

Class and protocol design

Reference code

GeoTrackingExample/GPXParser.swift:10 — the app-defined delegate contract

protocol GPXParserDelegate: AnyObject {
    func parser(_ parser: GPXParser, didFinishParsingFileWithAnchors anchors: [ARGeoAnchor])
}
Type Responsibility Depends on
ViewController Session, location, map, input, and visualization ARKit, RealityKit, MapKit
GPXParser Adapts XMLParserDelegate events into one completion callback with [ARGeoAnchor] XMLParser, GPXParserDelegate
GPXExporter Formats anchors into GPX text and writes it ARGeoAnchor
GeoAnchorWithAssociatedData Value pair of anchor and overlay, used for undo ARGeoAnchor, AnchorIndicator
AnchorIndicator MKCircle subclass that marks app-added overlays MapKit

Observed: AnchorIndicator exists so the map delegate and restartSession() can tell app overlays apart by type (GeoTrackingExample/ViewController.swift:189, GeoTrackingExample/ViewController.swift:323). The protocol is constrained to AnyObject so the parser can hold its delegate weak.

Access control

Symbol Access Verified effect Likely rationale
GPXParser internals (GeoTrackingExample/GPXParser.swift:19) private var Parse state is invisible outside the parser Inference: callers see only init?(contentsOf:), parse(), and the delegate callback.
GPXExporter templates and gpxWaypoint(from:) (GeoTrackingExample/GPXExporter.swift:14, GeoTrackingExample/GPXExporter.swift:40) private Only exportGeoAnchors(_:toFileWithURL:) is exposed Inference: the string templates are an implementation detail.
GPXParser.delegate (GeoTrackingExample/GPXParser.swift:16) implicit internal, weak Set by parseGPXFile(with:) Inference: avoids a retain cycle with the controller.
ViewController members (GeoTrackingExample/ViewController.swift:14) implicit internal Extensions in other files can use all outlets and state Inference: needed because the controller is split across files; private would block cross-file extensions.
GPXExporter.shared (GeoTrackingExample/GPXExporter.swift:12) implicit internal static let A shared instance; the initializer is not private, so other instances are possible Inference: convenience access, not an enforced singleton.

Reference code

GeoTrackingExample/GPXExporter.swift:10 — one public method over private templates

class GPXExporter {
    
    static let shared = GPXExporter()
    
    private let gpxPrefix = """
    <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
    <gpx xmlns="http://www.topografix.com/GPX/1/1" creator="Apple Inc.">

    """
    // ...
    func exportGeoAnchors(_ geoAnchors: [ARGeoAnchor], toFileWithURL url: URL) throws {
        // ...
    }
    // ...
}

Logic ownership and placement

Logic Owning type or file Placement rationale
Session configuration and reset ViewController.restartSession() Runs the geotracking configuration with .removeExistingAnchors and clears local and map state together (GeoTrackingExample/ViewController.swift:163).
Screen point → geo anchor ViewController.handleTapOnARView(_:), addGeoAnchor(at: SIMD3<Float>) Raycast, then getGeoLocation(forPoint:) (GeoTrackingExample/ViewController.swift:100, GeoTrackingExample/ViewController.swift:196).
Map point → geo anchor ViewController.handleTapOnMapView(_:) Converts the tap to a coordinate (GeoTrackingExample/ViewController.swift:111).
Visualization ViewController.session(_:didAdd:), Entity.placemarkEntity(for:) One path for every anchor source (GeoTrackingExample/Utilities.swift:33).
Undo ViewController.undoButtonTapped(_:) Uses the anchor/overlay pair to remove both (GeoTrackingExample/ViewController.swift:116).
GPX file I/O and sharing ViewController+LoadSaveAnchors.swift, GPXParser, GPXExporter UI flow in the extension, format logic in standalone types (GeoTrackingExample/ViewController+LoadSaveAnchors.swift:55).
Coaching UI ViewController+CoachingOverlay.swift Overlay setup and delegate callbacks (GeoTrackingExample/ViewController+CoachingOverlay.swift:35).

Design patterns

Pattern Source evidence Purpose or tradeoff
Delegate or data-source callbacks ViewController: UIViewController, ARSessionDelegate, CLLocationManagerDelegate, MKMapViewDelegate (GeoTrackingExample/ViewController.swift:14); GPXParserDelegate with a weak delegate (GeoTrackingExample/GPXParser.swift:10, GeoTrackingExample/GPXParser.swift:16) Framework and parser events flow back into one controller. The app’s own parser follows the same convention as the frameworks.

Removed: “View-controller organization” (inferred from the type name) and “Protocol-oriented abstraction”. The single app protocol, GPXParserDelegate, is a delegate callback contract with one conformer, not a substitution boundary.

Naming conventions

  • Types: framework-style nouns. GPXParser/GPXParserDelegate mirror XMLParser/XMLParserDelegate. GeoAnchorWithAssociatedData describes its contents. AnchorIndicator names the overlay’s role.
  • Methods: action handlers end in Tapped (menuButtonTapped, undoButtonTapped) or start with handleTapOn…. Commands are verb phrases (restartSession, addGeoAnchor(at:), saveAnchorsAsGPXFile, parseGPXFile(with:)). The delegate method uses the framework form parser(_:didFinishParsingFileWithAnchors:).
  • Files and extensions: ViewController+Feature.swift for each feature extension. Generic helpers and the shared-UI extension are in Utilities.swift.
  • Constants: a file-level GPXFileExtension constant (GeoTrackingExample/ViewController+LoadSaveAnchors.swift:15).

Architecture takeaways

  • Funnel every anchor source (AR tap, map tap, GPX file) into session.add(anchor:), and create visualizations only in session(_:didAdd:). One code path keeps the AR view and the map consistent.
  • Gate user actions on framework readiness (geoTrackingStatus.state == .localized) at the point of creation, not only in the UI.
  • Keep file-format code in small types with a delegate callback (GPXParser) or a single method (GPXExporter). Leave the UI flow in a view-controller extension.
  • Pair each framework object with the UI artifact it produced (GeoAnchorWithAssociatedData) so undo can remove both.
  • When adopting the scene lifecycle, move window-dependent code (root view controller swaps, URL handling) to the scene delegate. Here it remains in AppDelegate.

Source map

Source file Relevant symbols
GeoTrackingExample/ViewController.swift ViewController, viewDidLoad, restartSession(), addGeoAnchor, isGeoTrackingLocalized, session(_:didAdd:), session(_:didChange:)
GeoTrackingExample/ViewController+LoadSaveAnchors.swift showGPXFiles(), saveAnchorsAsGPXFile(_:), parseGPXFile(with:), GPXParserDelegate conformance
GeoTrackingExample/ViewController+CoachingOverlay.swift ARCoachingOverlayViewDelegate conformance, setupCoachingOverlay()
GeoTrackingExample/GPXParser.swift GPXParserDelegate, GPXParser
GeoTrackingExample/GPXExporter.swift GPXExporter
GeoTrackingExample/GeoAnchorWithAssociatedData.swift GeoAnchorWithAssociatedData
GeoTrackingExample/Utilities.swift AnchorIndicator, Entity.placemarkEntity(for:), alertUser, showToast
GeoTrackingExample/AppDelegate.swift AppDelegate
GeoTrackingExample/SceneDelegate.swift SceneDelegate
GeoTrackingExample/Info.plist CFBundleDocumentTypes, UIApplicationSceneManifest
GeoTrackingExample.xcodeproj/project.pbxproj IPHONEOS_DEPLOYMENT_TARGET