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

Creating a collaborative session

At a glance

Item Summary
Purpose Share one AR world among up to four nearby devices by sending ARSession.CollaborationData over MultipeerConnectivity, and place colored cubes that every participant sees.
App architecture A UIKit storyboard app. ViewController owns the ARView session configuration and creates a MultipeerSession, passing it four handler closures. MultipeerSession owns the MCSession, advertiser, and browser and reports peer events back through those closures.
Main patterns One view controller as the AR delegate and feature owner; framework delegate protocols on both the AR and networking sides; closures injected into the networking wrapper instead of a delegate protocol.
Project style Flat CollaborativeSession/ folder: app and scene delegates, ViewController plus a coaching-overlay extension, MultipeerSession, MessageLabel, and Utilities.
Execution model No actor or Task. MessageLabel and the AR-failure alert submit UI work with DispatchQueue.main.async. Networking callbacks run the injected handlers directly; the source does not establish their queue.
State/event model Delegate callbacks (ARSessionDelegate, MCSessionDelegate, browser/advertiser delegates, ARCoachingOverlayViewDelegate), closure handlers, and one key-value observation of arView.session.identifier.
Key frameworks/packages ARKit, RealityKit, MultipeerConnectivity, UIKit, Foundation. No Swift package is declared.

Project structure

CollaborativeSession.xcodeproj/          one iOS application target, Swift 5
CollaborativeSession/
├── AppDelegate.swift                    @UIApplicationMain; ARKit support check; scene configuration
├── SceneDelegate.swift                  empty UIWindowSceneDelegate (storyboard supplies the window)
├── ViewController.swift                 ARSessionDelegate; session config, anchors, peer handlers
├── ViewController+CoachingOverlay.swift ARCoachingOverlayViewDelegate + setup
├── MultipeerSession.swift               MCSession / advertiser / browser wrapper
├── MessageLabel.swift                   UILabel that schedules show/hide on the main queue
├── Utilities.swift                      MeshResource axes helper, UUID -> color
├── Base.lproj/Main.storyboard
└── Info.plist                           scene manifest, Bonjour service, local-network usage

Structure observations

  • The app uses a scene manifest whose default configuration names SceneDelegate and the Main storyboard (CollaborativeSession/Info.plist:33, CollaborativeSession/Info.plist:45). SceneDelegate contains only empty lifecycle methods (CollaborativeSession/SceneDelegate.swift:10), and AppDelegate returns a UISceneConfiguration named “Default Configuration” (CollaborativeSession/AppDelegate.swift:38).
  • All feature logic is in ViewController; coaching-overlay behavior is split into a conformance extension in its own file (CollaborativeSession/ViewController+CoachingOverlay.swift:11).
  • MultipeerSession has no ARKit import; it moves opaque Data between peers, and ViewController encodes and decodes the AR payload (CollaborativeSession/MultipeerSession.swift:8, CollaborativeSession/ViewController.swift:130).
  • Info.plist declares the _ar-collab._tcp Bonjour service and a local-network usage string, matching MultipeerSession.serviceType = "ar-collab" (CollaborativeSession/Info.plist:75, CollaborativeSession/Info.plist:27, CollaborativeSession/MultipeerSession.swift:11).
  • The target builds with SWIFT_VERSION = 5.0 and an iOS 15.0 deployment target, while the DocC record lists iOS 13.0 (CollaborativeSession.xcodeproj/project.pbxproj:346, CollaborativeSession.xcodeproj/project.pbxproj:338).

Overall architecture

Reference code

CollaborativeSession/ViewController.swift:31 — session and networking setup

    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)

        arView.session.delegate = self

        // Turn off ARView's automatically-configured session
        // to create and set up your own configuration.
        arView.automaticallyConfigureSession = false
        
        configuration = ARWorldTrackingConfiguration()

        // Enable a collaborative session.
        configuration?.isCollaborationEnabled = true
        // ...
        // Begin the session.
        arView.session.run(configuration!)
        // ...
        setupCoachingOverlay()
        
        // Start looking for other players via MultiPeerConnectivity.
        multipeerSession = MultipeerSession(receivedDataHandler: receivedData, peerJoinedHandler:
                                            peerJoined, peerLeftHandler: peerLeft, peerDiscoveredHandler: peerDiscovered)
        // ...
    }

Interpretation

Observed: ViewController is the hub. It configures the session with isCollaborationEnabled = true, receives collaboration data as the session delegate, and creates the networking wrapper. Dependencies point from ViewController to MultipeerSession; the wrapper knows nothing about ARKit or the view controller type, only the closure signatures.

Inference: injecting closures keeps MultipeerSession reusable for any payload, at the cost of having the view controller own both AR and networking policy (such as the four-peer limit).

Ownership and state

Ownership evidence

CollaborativeSession/MultipeerSession.swift:10 — MultipeerSession stored state and init

class MultipeerSession: NSObject {
    static let serviceType = "ar-collab"
    
    private let myPeerID = MCPeerID(displayName: UIDevice.current.name)
    private var session: MCSession!
    private var serviceAdvertiser: MCNearbyServiceAdvertiser!
    private var serviceBrowser: MCNearbyServiceBrowser!
    
    private let receivedDataHandler: (Data, MCPeerID) -> Void
    private let peerJoinedHandler: (MCPeerID) -> Void
    private let peerLeftHandler: (MCPeerID) -> Void
    private let peerDiscoveredHandler: (MCPeerID) -> Bool
    // ...
}
Owner Object or state Relationship Mutation authority
Storyboard ViewController, ARView, MessageLabel, restart button Outlets connected from Main.storyboard (CollaborativeSession/ViewController.swift:15) UIKit
ViewController MultipeerSession Creates it in viewDidAppear(_:) and stores it in var multipeerSession (CollaborativeSession/ViewController.swift:19, CollaborativeSession/ViewController.swift:64) ViewController
ViewController peerSessionIDs: [MCPeerID: String] Maps each peer to its AR session ID (CollaborativeSession/ViewController.swift:25) Written in receivedData and peerLeft
ViewController sessionIDObservation Stores the KVO token for arView.session.identifier (CollaborativeSession/ViewController.swift:27, CollaborativeSession/ViewController.swift:53) ViewController
MultipeerSession MCSession, advertiser, browser Creates, delegates to self, and starts them in init (CollaborativeSession/MultipeerSession.swift:34, CollaborativeSession/MultipeerSession.swift:37, CollaborativeSession/MultipeerSession.swift:41) Only MultipeerSession (private)
MultipeerSession Four handler closures private let, supplied by the initializer (CollaborativeSession/MultipeerSession.swift:23) Immutable after init

Observed: the handlers are unapplied method references (receivedData, peerJoined, and so on), which capture ViewController strongly, and ViewController strongly holds multipeerSession. The KVO closure also refers to self without a weak capture while ViewController stores its token (CollaborativeSession/ViewController.swift:57). Inference: both form reference cycles; they are harmless here because the single view controller lives for the app’s lifetime.

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
Main-queue scheduling DispatchQueue.main.async inside MessageLabel.displayMessage(_:duration:) Every text and visibility change is submitted to the main queue, so callers on any queue can post messages CollaborativeSession/MessageLabel.swift:23, CollaborativeSession/MessageLabel.swift:30
Delayed main-queue work DispatchQueue.main.asyncAfter with a tag check Hides the label after duration only if no newer message replaced it CollaborativeSession/MessageLabel.swift:38, CollaborativeSession/MessageLabel.swift:40
Main-queue scheduling DispatchQueue.main.async in session(_:didFailWithError:) Presents the failure alert and restart action on the main queue CollaborativeSession/ViewController.swift:204
Callback delivery MCSessionDelegate, browser, and advertiser methods call the injected handlers synchronously receivedData, peerJoined, peerLeft, and peerDiscovered run in whatever context MultipeerConnectivity calls the delegate; the source does not hop or name a queue CollaborativeSession/MultipeerSession.swift:68, CollaborativeSession/MultipeerSession.swift:75, CollaborativeSession/MultipeerSession.swift:99
Shared-state safety None peerSessionIDs is mutated from those handlers with no lock, queue, or actor; thread safety is not established by source CollaborativeSession/ViewController.swift:156, CollaborativeSession/ViewController.swift:187
Liveness UIApplication.shared.isIdleTimerDisabled = true Keeps the screen awake during the session CollaborativeSession/ViewController.swift:68
Compiler mode SWIFT_VERSION = 5.0 Swift 5 language mode; no concurrency annotations appear CollaborativeSession.xcodeproj/project.pbxproj:346

Reference code

CollaborativeSession/MessageLabel.swift:20 — UI updates are queued to main

    func displayMessage(_ text: String, duration: TimeInterval = 3.0) {
        guard !ignoreMessages else { return }
        guard !text.isEmpty else {
            DispatchQueue.main.async {
                self.isHidden = true
                self.text = ""
            }
            return
        }
        
        DispatchQueue.main.async {
            self.isHidden = false
            self.text = text
            
            // Use a tag to tell if the label has been updated.
            let tag = self.tag + 1
            self.tag = tag
            
            DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
                // Do not hide if this method is called again before this block kicks in.
                if self.tag == tag {
                    self.isHidden = true
                }
            }
        }
    }

Interpretation: the label, not its callers, owns the main-queue handoff, which is what makes it safe to call from peer callbacks. The tag counter is a small “latest message wins” guard. The ignoreMessages read happens before the hop, so it runs on the caller’s queue.

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
AR to network session(_:didOutputCollaborationData:) → NSKeyedArchiver → sendToAllPeers(_:reliably:) Collaboration data is archived and sent reliably only when its priority is .critical CollaborativeSession/ViewController.swift:127, CollaborativeSession/ViewController.swift:133
Network to AR receivedData(_:from:) → NSKeyedUnarchiver → arView.session.update(with:) Incoming collaboration data merges the peer’s map into the local session CollaborativeSession/ViewController.swift:141, CollaborativeSession/ViewController.swift:142
Side channel UTF-8 "SessionID:<uuid>" strings Peers learn each other’s AR session ID so anchors can be removed when a peer leaves or restarts CollaborativeSession/ViewController.swift:146, CollaborativeSession/ViewController.swift:244
Observation KVO observe(\.arView.session.identifier) When the local session ID changes, the new ID is sent to connected peers CollaborativeSession/ViewController.swift:53
Rendering ARAnchor → AnchorEntity → ModelEntity Participant anchors get axes and a sphere; placement anchors get a cube colored by session ID CollaborativeSession/ViewController.swift:97, CollaborativeSession/ViewController.swift:120
Framework import UIKit, RealityKit, ARKit, MultipeerConnectivity Imported by ViewController CollaborativeSession/ViewController.swift:8, CollaborativeSession/ViewController.swift:11
Framework import MultipeerConnectivity only The networking wrapper’s single import CollaborativeSession/MultipeerSession.swift:8
Package declaration None One application target, no package references CollaborativeSession.xcodeproj/project.pbxproj:123

No Combine or Swift concurrency appears in the source.

Class and protocol design

Reference code

CollaborativeSession/MultipeerSession.swift:64 — delegate events become handler calls

extension MultipeerSession: MCSessionDelegate {
    
    func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
        if state == .connected {
            peerJoinedHandler(peerID)
        } else if state == .notConnected {
            peerLeftHandler(peerID)
        }
    }
    
    func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
        receivedDataHandler(data, peerID)
    }
    // ...
}
Type Responsibility Depends on
ViewController AR session configuration, anchor placement and rendering, collaboration encode/decode, peer policy ARView, MultipeerSession, MessageLabel
MultipeerSession Advertise, browse, invite, accept, and send Data to peers MCSession, MCNearbyServiceAdvertiser, MCNearbyServiceBrowser
MessageLabel Thread-tolerant transient status messages UILabel, main queue
AppDelegate / SceneDelegate Launch check and scene configuration; no feature state UIApplicationDelegate, UIWindowSceneDelegate
Utilities extensions Coordinate-axes entity and deterministic UUID color RealityKit, UIKit

Observed: the sample declares no protocol of its own. MultipeerSession adapts three MultipeerConnectivity delegate protocols into four closures. The browser auto-invites a discovered peer only when peerDiscoveredHandler returns true (CollaborativeSession/MultipeerSession.swift:99), and the advertiser accepts every invitation (CollaborativeSession/MultipeerSession.swift:116).

Access control

Symbol Access Verified effect Likely rationale
MultipeerSession.myPeerID, session, serviceAdvertiser, serviceBrowser (CollaborativeSession/MultipeerSession.swift:13) private Only the wrapper touches MultipeerConnectivity objects; callers use sendToPeers, sendToAllPeers, and connectedPeers Inference: hides the transport behind a small API.
Handler closures (CollaborativeSession/MultipeerSession.swift:18) private let Set once in init; cannot be swapped later Inference: fixes the callback wiring for the session’s lifetime.
browser(_:foundPeer:withDiscoveryInfo:), browser(_:lostPeer:) (CollaborativeSession/MultipeerSession.swift:97, CollaborativeSession/MultipeerSession.swift:105) public Has no wider effect than internal because the enclosing class is internal Inference: a leftover modifier, not a module boundary.
ViewController.removeAllAnchorsOriginatingFromARSessionWithID(_:), sendARSessionIDTo(peers:) (CollaborativeSession/ViewController.swift:231, CollaborativeSession/ViewController.swift:241) private Callable only inside ViewController.swift, so not from the coaching-overlay extension file Inference: keeps the session-ID protocol internal to the controller.
ViewController.multipeerSession, peerSessionIDs, configuration (CollaborativeSession/ViewController.swift:19) implicit internal Readable and writable across the module Inference: no external writer exists in source; the defaults were left as is.

Reference code

CollaborativeSession/ViewController.swift:241 — private session-ID message

    private func sendARSessionIDTo(peers: [MCPeerID]) {
        guard let multipeerSession = multipeerSession else { return }
        let idString = arView.session.identifier.uuidString
        let command = "SessionID:" + idString
        if let commandData = command.data(using: .utf8) {
            multipeerSession.sendToPeers(commandData, reliably: true, peers: peers)
        }
    }

Logic ownership and placement

Logic Owning type or file Placement rationale
ARKit support check AppDelegate.application(_:didFinishLaunchingWithOptions:) Fails fast with fatalError if world tracking is unsupported (CollaborativeSession/AppDelegate.swift:18).
Collaboration send policy ViewController.session(_:didOutputCollaborationData:) Skips sending when no peers are connected; reliable delivery only for critical data (CollaborativeSession/ViewController.swift:129).
Peer limit ViewController.peerDiscovered(_:) Rejects a discovered peer when more than three are connected (CollaborativeSession/ViewController.swift:163).
Anchor cleanup by peer ViewController.peerLeft(_:) and receivedData(_:from:) Removes anchors whose sessionIdentifier matches the departed or restarted peer’s old session (CollaborativeSession/ViewController.swift:185, CollaborativeSession/ViewController.swift:152).
Object placement ViewController.handleTap(recognizer:) Raycasts to a horizontal estimated plane and adds a named ARAnchor; rendering happens when session(_:didAdd:) sees that name (CollaborativeSession/ViewController.swift:80, CollaborativeSession/ViewController.swift:108).
Coaching overlay ViewController+CoachingOverlay.swift Hides status UI while coaching and resets tracking on request (CollaborativeSession/ViewController+CoachingOverlay.swift:13).
Per-peer color UUID.toRandomColor() Deterministic color from the session ID’s first four bytes (CollaborativeSession/Utilities.swift:48).

Design patterns

Pattern Source evidence Purpose or tradeoff
View-controller organization class ViewController: UIViewController, ARSessionDelegate with storyboard outlets, viewDidAppear setup, and all feature handlers (CollaborativeSession/ViewController.swift:13, CollaborativeSession/ViewController.swift:31) The UIKit controller is the single owner of AR, networking, and UI policy; simple, but every concern lands in one type.
Delegate or data-source callbacks ARSessionDelegate, ARCoachingOverlayViewDelegate, and three MultipeerConnectivity delegate protocols (CollaborativeSession/ViewController+CoachingOverlay.swift:11, CollaborativeSession/MultipeerSession.swift:64, CollaborativeSession/MultipeerSession.swift:95, CollaborativeSession/MultipeerSession.swift:111) Framework events reach the app through delegates.
Closure-based handler injection MultipeerSession.init(receivedDataHandler:peerJoinedHandler:peerLeftHandler:peerDiscoveredHandler:) (CollaborativeSession/MultipeerSession.swift:23) The wrapper reports events through injected closures, so it depends on no app type; one handler also returns a decision ((MCPeerID) -> Bool).

Main application flow

Reference code

CollaborativeSession/ViewController.swift:127 — outgoing collaboration data

    func session(_ session: ARSession, didOutputCollaborationData data: ARSession.CollaborationData) {
        guard let multipeerSession = multipeerSession else { return }
        if !multipeerSession.connectedPeers.isEmpty {
            guard let encodedData = try? NSKeyedArchiver.archivedData(withRootObject: data, requiringSecureCoding: true)
            else { fatalError("Unexpectedly failed to encode collaboration data.") }
            // Use reliable mode if the data is critical, and unreliable mode if the data is optional.
            let dataIsCritical = data.priority == .critical
            multipeerSession.sendToAllPeers(encodedData, reliably: dataIsCritical)
        } else {
            print("Deferred sending collaboration to later because there are no peers.")
        }
    }

CollaborativeSession/MultipeerSession.swift:50 — transport send

    func sendToPeers(_ data: Data, reliably: Bool, peers: [MCPeerID]) {
        guard !peers.isEmpty else { return }
        do {
            try session.send(data, toPeers: peers, with: reliably ? .reliable : .unreliable)
        } catch {
            print("error sending data to peers \(peers): \(error.localizedDescription)")
        }
    }

CollaborativeSession/MultipeerSession.swift:75 — receive delegate forwards to the handler

    func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
        receivedDataHandler(data, peerID)
    }

CollaborativeSession/ViewController.swift:140 — incoming data merged into the local session

    func receivedData(_ data: Data, from peer: MCPeerID) {
        if let collaborationData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: ARSession.CollaborationData.self, from: data) {
            arView.session.update(with: collaborationData)
            return
        }
        // ...
    }

Observed: the same receive path also handles the "SessionID:" string messages when the payload does not decode as collaboration data. The transport sends nothing until at least one peer is connected.

Naming conventions

  • Types: MultipeerSession names the transport it wraps; MessageLabel names a specialized UILabel; the controller keeps the template name ViewController.
  • Protocols: none declared locally.
  • Methods: handler closures are named …Handler (receivedDataHandler, peerJoinedHandler), and the matching controller methods use event names (receivedData(_:from:), peerJoined(_:), peerLeft(_:), peerDiscovered(_:)). Send methods name their audience (sendToAllPeers, sendToPeers, sendARSessionIDTo(peers:)). Long descriptive private names spell out intent (removeAllAnchorsOriginatingFromARSessionWithID(_:)).
  • Files and extensions: ViewController+CoachingOverlay.swift holds one protocol conformance; MultipeerConnectivity conformances are separate extensions in MultipeerSession.swift.

Architecture takeaways

  • Wrapping a framework transport behind a small Data-in, closures-out API keeps networking free of AR types; the controller owns all payload encoding.
  • Collaboration data priority maps directly to delivery mode: reliable for critical data, unreliable otherwise.
  • Tracking each peer’s AR session ID over a side channel is what lets the app remove a departed peer’s anchors.
  • Moving the main-queue hop into MessageLabel makes UI messages safe from any callback, but shared controller state such as peerSessionIDs has no matching protection.
  • Unapplied method references and a strong KVO capture create reference cycles; that is acceptable only because the controller lives as long as the app.

Source map

Source file Relevant symbols
CollaborativeSession/AppDelegate.swift AppDelegate, application(_:didFinishLaunchingWithOptions:), application(_:configurationForConnecting:options:)
CollaborativeSession/SceneDelegate.swift SceneDelegate
CollaborativeSession/ViewController.swift ViewController, viewDidAppear(_:), handleTap(recognizer:), session(_:didAdd:), session(_:didOutputCollaborationData:), receivedData(_:from:), peerDiscovered(_:), peerJoined(_:), peerLeft(_:), session(_:didFailWithError:), sendARSessionIDTo(peers:)
CollaborativeSession/ViewController+CoachingOverlay.swift ARCoachingOverlayViewDelegate, setupCoachingOverlay()
CollaborativeSession/MultipeerSession.swift MultipeerSession, sendToAllPeers(_:reliably:), sendToPeers(_:reliably:peers:), MCSessionDelegate, MCNearbyServiceBrowserDelegate, MCNearbyServiceAdvertiserDelegate
CollaborativeSession/MessageLabel.swift MessageLabel, displayMessage(_:duration:)
CollaborativeSession/Utilities.swift MeshResource.generateCoordinateSystemAxes(length:thickness:), UUID.toRandomColor()
CollaborativeSession/Info.plist UIApplicationSceneManifest, NSBonjourServices, NSLocalNetworkUsageDescription
CollaborativeSession.xcodeproj/project.pbxproj Target, SWIFT_VERSION, IPHONEOS_DEPLOYMENT_TARGET