Creating a multiuser AR experience
At a glance
| Item | Summary |
|---|---|
| Purpose | One device shares its ARWorldMap with nearby peers so they relocalize into the same space. After that, devices share placed ARAnchors so each one renders the same virtual content. |
| App architecture | Storyboard UIKit app with one ViewController. It runs the ARSCNView session, owns a MultipeerSession wrapper, and encodes and decodes the two message types. |
| Main patterns | View-controller organization. ARKit, SceneKit, and MultipeerConnectivity delegate callbacks, with MC callbacks turned into one closure handler. |
| Project style | Flat ARMultiuser/ folder: controller, networking wrapper, a button subclass, and a WorldMappingStatus description extension |
| Execution model | Framework callbacks (ARSession, world-map completion, MCSession) plus one DispatchQueue.main.async hop for the error alert. There is no Swift concurrency. |
| State/event model | Delegate callbacks update labels and button state directly. Network payloads are NSKeyedArchiver archives with secure coding. |
| Key frameworks/packages | ARKit, SceneKit, MultipeerConnectivity, UIKit |
Project structure
ARMultiuser/
├── AppDelegate.swift // @UIApplicationMain, scene configuration
├── SceneDelegate.swift // empty UIWindowSceneDelegate (storyboard window)
├── ViewController.swift // AR session, map/anchor send + receive, status UI
├── MultipeerSession.swift // MCSession wrapper with one received-data closure
├── RoundedButton.swift // styled UIButton
├── Utilities.swift // ARFrame.WorldMappingStatus description
└── Info.plist // UIApplicationSceneManifest → SceneDelegate, Main storyboard
Structure observations
- The storyboard creates the window through the scene manifest (
ARMultiuser/Info.plist:29).SceneDelegate.scene(_:willConnectTo:options:)only checks the scene type (ARMultiuser/SceneDelegate.swift:15). - All AR and networking coordination is in
ViewController.swift.MultipeerSession.swiftcontains only MultipeerConnectivity code and knows nothing about ARKit.
Overall architecture
flowchart LR
Storyboard["Main storyboard"] --> VC["ViewController"]
VC --> SceneView["ARSCNView / ARSession"]
VC --> MS["MultipeerSession"]
MS --> MC["MCSession + advertiser + browser"]
MS -->|"receivedDataHandler"| VC
SceneView -->|"ARSessionDelegate / ARSCNViewDelegate"| VC
Reference code
ARMultiuser/ViewController.swift:29 — ViewController creates the networking wrapper
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
// ...
var multipeerSession: MultipeerSession!
override func viewDidLoad() {
super.viewDidLoad()
multipeerSession = MultipeerSession(receivedDataHandler: receivedData)
}
// ...
}Interpretation
ViewController is the only coordinator. It passes its receivedData method to MultipeerSession as a closure and sets itself as the AR session delegate (ARMultiuser/ViewController.swift:53). Events come back from both frameworks into the same controller.
Ownership and state
classDiagram
ViewController *-- MultipeerSession : multipeerSession
ViewController o-- ARSCNView : weak outlet
ViewController --> ARSession : delegate
MultipeerSession *-- MCSession : session
MultipeerSession *-- MCNearbyServiceAdvertiser : serviceAdvertiser
MultipeerSession *-- MCNearbyServiceBrowser : serviceBrowser
Ownership evidence
ARMultiuser/MultipeerSession.swift:25 — MultipeerSession.init
init(receivedDataHandler: @escaping (Data, MCPeerID) -> Void ) {
self.receivedDataHandler = receivedDataHandler
super.init()
session = MCSession(peer: myPeerID, securityIdentity: nil, encryptionPreference: .required)
session.delegate = self
serviceAdvertiser = MCNearbyServiceAdvertiser(peer: myPeerID, discoveryInfo: nil, serviceType: MultipeerSession.serviceType)
serviceAdvertiser.delegate = self
serviceAdvertiser.startAdvertisingPeer()
serviceBrowser = MCNearbyServiceBrowser(peer: myPeerID, serviceType: MultipeerSession.serviceType)
serviceBrowser.delegate = self
serviceBrowser.startBrowsingForPeers()
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
ViewController |
multipeerSession |
Creates in viewDidLoad and stores |
ViewController |
ViewController |
mapProvider: MCPeerID? |
Set when a world map arrives (ARMultiuser/ViewController.swift:179). Read to build status messages. |
ViewController |
ViewController |
sceneView and status outlets |
Weak storyboard outlets | Storyboard. The controller updates text and enabled state. |
MultipeerSession |
MCSession, advertiser, browser, receivedDataHandler |
Creates in init, all private |
MultipeerSession |
ARSession (via sceneView) |
World map and anchors | The controller runs, pauses, and resets it, and adds anchors | ViewController |
Inference: the receivedData method reference captures ViewController strongly, so the controller and its session keep each other alive. For the app’s only screen, this matches 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 |
Shows the AR-session failure alert and its restart action | ARMultiuser/ViewController.swift:124 |
| Framework callback | getCurrentWorldMap completion |
Archives the map and sends it to all peers inside the completion. The source does not set a callback queue. | ARMultiuser/ViewController.swift:157 |
| Framework callback | MCSessionDelegate.session(_:didReceive:fromPeer:) |
Calls receivedDataHandler directly. receivedData then runs or adds to the AR session without an explicit queue hop. |
ARMultiuser/MultipeerSession.swift:57, ARMultiuser/ViewController.swift:176 |
| Framework callback | ARSessionDelegate.session(_:didUpdate:) |
Updates sendMapButton and the labels directly. The source sets no delegate queue. |
ARMultiuser/ViewController.swift:83 |
| Lifetime | viewWillDisappear |
Pauses the AR session. Nothing in the source stops MC advertising or browsing. | ARMultiuser/ViewController.swift:66 |
No source-visible lock or serial queue protects mapProvider. It is written in receivedData and read in updateSessionInfoLabel.
Reference code
ARMultiuser/ViewController.swift:157 — world-map completion sends to peers
@IBAction func shareSession(_ button: UIButton) {
sceneView.session.getCurrentWorldMap { worldMap, error in
guard let map = worldMap
else { print("Error: \(error!.localizedDescription)"); return }
guard let data = try? NSKeyedArchiver.archivedData(withRootObject: map, requiringSecureCoding: true)
else { fatalError("can't encode map") }
self.multipeerSession.sendToAllPeers(data)
}
}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 |
|---|---|---|---|
| State propagation | Closure handler | MultipeerSession forwards every received payload to ViewController.receivedData |
ARMultiuser/MultipeerSession.swift:57 |
| State propagation | AR delegate callbacks | Mapping status turns on sendMapButton only when the map is .extending or .mapped and peers are connected |
ARMultiuser/ViewController.swift:88 |
| State propagation | Anchor → node | A received or local ARAnchor named with the panda prefix gets its model in renderer(_:didAdd:for:) |
ARMultiuser/ViewController.swift:72 |
| Wire format | NSKeyedArchiver with secure coding |
Local ARWorldMap and ARAnchor objects are archived. The receiver tries to unarchive a world map first, then an anchor. |
ARMultiuser/ViewController.swift:151, ARMultiuser/ViewController.swift:171, ARMultiuser/ViewController.swift:180 |
| Framework import | ARKit, SceneKit, MultipeerConnectivity |
Imported by the controller | ARMultiuser/ViewController.swift:10 |
| Framework import | MultipeerConnectivity |
Imported by the networking wrapper | ARMultiuser/MultipeerSession.swift:8 |
Platform boundary
The project targets iPhone and iPad (TARGETED_DEVICE_FAMILY = "1,2", ARMultiuser.xcodeproj/project.pbxproj:344).
Class and protocol design
classDiagram
ViewController ..|> ARSCNViewDelegate
ViewController ..|> ARSessionDelegate
MultipeerSession ..|> MCSessionDelegate
MultipeerSession ..|> MCNearbyServiceBrowserDelegate
MultipeerSession ..|> MCNearbyServiceAdvertiserDelegate
ViewController --> MultipeerSession : sendToAllPeers
Reference code
ARMultiuser/MultipeerSession.swift:78 — browser invites every discovered peer, and the advertiser accepts every invitation
extension MultipeerSession: MCNearbyServiceBrowserDelegate {
public func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String]?) {
// Invite the new peer to the session.
browser.invitePeer(peerID, to: session, withContext: nil, timeout: 10)
}
public func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
// This app doesn't do anything with non-invited peers, so there's nothing to do here.
}
}| Type | Responsibility | Depends on |
|---|---|---|
ViewController |
AR session lifecycle, tap-to-place, map sharing, payload decoding, status UI | ARSCNView, MultipeerSession |
MultipeerSession |
Advertise, browse, auto-invite, auto-accept, reliable send to all peers | MCSession |
ARFrame.WorldMappingStatus extension |
Human-readable status text | ARKit |
RoundedButton |
Styled button over the camera view | UIButton |
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
MultipeerSession.session, serviceAdvertiser, serviceBrowser |
private var |
Only the wrapper can reach the MC objects. Callers use sendToAllPeers and connectedPeers. |
Inference: hides MultipeerConnectivity from the controller |
MultipeerSession.receivedDataHandler |
private let |
Fixed at init |
Inference: one consumer for the session’s lifetime |
MultipeerSession browser delegate methods |
public |
Inside an internal type, public does not make them visible outside the module |
Inference: carried over from protocol requirements, with no effect on the boundary |
ViewController.updateSessionInfoLabel, loadRedPandaModel |
private |
Helpers available only inside the controller | Inference: implementation details of the status UI and content |
ViewController.multipeerSession, mapProvider |
implicit internal |
Visible to the whole module | Inference: no wider encapsulation was needed in a single-screen app |
Reference code
ARMultiuser/MultipeerSession.swift:14 — MultipeerSession private state
class MultipeerSession: NSObject {
static let serviceType = "ar-multi-sample"
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
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Deciding when a map is shareable | ViewController.session(_:didUpdate:) |
Combines AR mapping status with the peer count (ARMultiuser/ViewController.swift:84) |
| Placing shared content | ViewController.handleSceneTap |
Adds an anchor locally and sends the same anchor to peers. Rendering happens in the anchor-to-node callback, so local and remote anchors take the same path (ARMultiuser/ViewController.swift:148). |
| Relocalizing into a received map | ViewController.receivedData |
Reruns the session with initialWorldMap and resets tracking and anchors (ARMultiuser/ViewController.swift:175) |
| Peer admission | MultipeerSession |
Invites every discovered peer and accepts every invitation (ARMultiuser/MultipeerSession.swift:94) |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | ARMultiuser/ViewController.swift:13, ARMultiuser/ViewController.swift:29 |
One controller creates the networking wrapper and handles AR and network events. Simple, but all coordination sits in one type. |
| Delegate or data-source callbacks | ARMultiuser/MultipeerSession.swift:50, ARMultiuser/ViewController.swift:71 |
MC delegate callbacks are turned into one closure. ARKit and SceneKit delegate callbacks drive status UI and content. |
Main application flow
sequenceDiagram
actor User
participant Host as ViewController
participant AR as ARSession
participant MS as MultipeerSession
participant Guest as Peer ViewController
User->>Host: shareSession
Host->>AR: getCurrentWorldMap
AR-->>Host: worldMap
Host->>MS: sendToAllPeers(archived map)
MS-->>Guest: receivedDataHandler(data, peer)
Guest->>Guest: run(initialWorldMap), mapProvider = peer
Reference code
ARMultiuser/ViewController.swift:162 — host archives and sends the map
@IBAction func shareSession(_ button: UIButton) {
sceneView.session.getCurrentWorldMap { worldMap, error in
guard let map = worldMap
else { print("Error: \(error!.localizedDescription)"); return }
guard let data = try? NSKeyedArchiver.archivedData(withRootObject: map, requiringSecureCoding: true)
else { fatalError("can't encode map") }
self.multipeerSession.sendToAllPeers(data)
}
}ARMultiuser/MultipeerSession.swift:57 — received data is forwarded to the handler
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
receivedDataHandler(data, peerID)
}ARMultiuser/ViewController.swift:176 — guest relocalizes into the received map
func receivedData(_ data: Data, from peer: MCPeerID) {
do {
if let worldMap = try NSKeyedUnarchiver.unarchivedObject(ofClass: ARWorldMap.self, from: data) {
// Run the session with the received world map.
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
configuration.initialWorldMap = worldMap
sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
// Remember who provided the map for showing UI feedback.
mapProvider = peer
// ...
}
} catch {
print("can't decode data recieved from \(peer)")
}
}Naming conventions
- Types:
MultipeerSessionnames the framework session it wraps.RoundedButtonnames its appearance. - Protocols: no local protocols. Framework delegate conformances are grouped in
extensionblocks. - Methods:
@IBActionmethods describe user intent (shareSession,handleSceneTap,resetTracking). Handlers use thereceived…prefix.update…Labelnames refresh UI. - Files and extensions: one primary type per file.
Utilities.swiftholds a small system-type extension.
Architecture takeaways
- Sharing a world map is a one-time bootstrap. After that, only small anchor messages are sent, and both local and remote anchors are rendered by the same callback.
- A thin networking wrapper with one closure keeps MultipeerConnectivity out of the controller. Message dispatch, though, depends on trying to unarchive each type in turn instead of an explicit message envelope.
- Mapping status and peer count together decide when the share button is enabled. The rule lives in the AR frame callback.
- Only the error alert has an explicit main-queue hop. The other callbacks update state without a source-visible queue contract.
Source map
| Source file | Relevant symbols |
|---|---|
ARMultiuser/AppDelegate.swift |
AppDelegate, application(_:configurationForConnecting:options:) |
ARMultiuser/SceneDelegate.swift |
SceneDelegate |
ARMultiuser/ViewController.swift |
ViewController, shareSession, handleSceneTap, receivedData, mapProvider, updateSessionInfoLabel |
ARMultiuser/MultipeerSession.swift |
MultipeerSession, sendToAllPeers, MC delegate extensions |
ARMultiuser/Utilities.swift |
ARFrame.WorldMappingStatus.description |
ARMultiuser/RoundedButton.swift |
RoundedButton |
ARMultiuser/Info.plist |
UIApplicationSceneManifest |
ARMultiuser.xcodeproj/project.pbxproj |
TARGETED_DEVICE_FAMILY |