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

Occluding virtual content with people

At a glance

Item Summary
Purpose Place a RealityKit model on a horizontal plane and toggle ARKit’s personSegmentationWithDepth frame semantics so people in the camera feed occlude the virtual vase.
App architecture A single-scene UIKit app. AppDelegate returns the scene configuration, SceneDelegate adopts the storyboard window, and one storyboard-instantiated ViewController owns the ARView outlet, loads the model, and reconfigures the running session on each tap.
Main patterns Delegate or data-source callbacks (UIKit application and scene lifecycle delegates)
Project style One app target with a flat PeopleOcclusion/ folder: two lifecycle delegates, one view controller, one label subclass, and storyboards. The vase.usdz asset sits at the project root and is bundled as a resource.
Execution model UIKit callbacks (viewDidLoad, viewDidAppear, a tap gesture action). The label schedules its show and hide work on DispatchQueue.main. No Swift concurrency appears.
State/event model Direct mutation: the view controller reads the session’s current configuration, edits frameSemantics, and re-runs the session. Interface Builder wires outlets, the tap action, and the coaching overlay.
Key frameworks/packages Swift modules UIKit, RealityKit, ARKit; no packages.

Project structure

PeopleOcclusion.xcodeproj        # 1 iOS app target
PeopleOcclusion/
├── AppDelegate.swift            # @UIApplicationMain, scene configuration
├── SceneDelegate.swift          # UIWindowSceneDelegate (storyboard window)
├── ViewController.swift         # ARView outlet, model load, occlusion toggle
├── RoundedLabel.swift           # @IBDesignable feedback label
├── Base.lproj/Main.storyboard   # ARView, label, coaching overlay, tap gesture
└── Info.plist                   # scene manifest, camera usage, arkit capability
vase.usdz                        # model resource

Structure observations

  • The project has one application target (PeopleOcclusion.xcodeproj/project.pbxproj:133) for device families 1,2 (PeopleOcclusion.xcodeproj/project.pbxproj:358) with an iOS 15 deployment target (PeopleOcclusion.xcodeproj/project.pbxproj:270).
  • The storyboard carries most of the wiring: the root view’s class is RealityKit’s ARView (PeopleOcclusion/Base.lproj/Main.storyboard:14), an ARCoachingOverlayView takes that view as its sessionProvider (PeopleOcclusion/Base.lproj/Main.storyboard:39), and a tap recognizer targets onTap: (PeopleOcclusion/Base.lproj/Main.storyboard:62).
  • Info.plist declares a single-scene manifest whose default configuration names SceneDelegate and the Main storyboard (PeopleOcclusion/Info.plist:37, PeopleOcclusion/Info.plist:39), and requires the arkit device capability (PeopleOcclusion/Info.plist:51).
  • vase.usdz lives at the project root and is copied as a bundle resource (PeopleOcclusion.xcodeproj/project.pbxproj:174).

Overall architecture

Reference code

PeopleOcclusion/ViewController.swift:43 — the whole feature: edit the running configuration’s frame semantics and re-run

    fileprivate func togglePeopleOcclusion() {
        // RealityKit configures the session automatically, which may not have happened
        // yet when the view appears. There's nothing to toggle until it has; tapping the
        // view toggles people occlusion once the session is running.
        guard let config = arView.session.configuration as? ARWorldTrackingConfiguration else { return }
        guard ARWorldTrackingConfiguration.supportsFrameSemantics(.personSegmentationWithDepth) else {
            fatalError("People occlusion is not supported on this device.")
        }
        switch config.frameSemantics {
        case [.personSegmentationWithDepth]:
            config.frameSemantics.remove(.personSegmentationWithDepth)
            messageLabel.displayMessage("People occlusion off", duration: 1.0)
        default:
            config.frameSemantics.insert(.personSegmentationWithDepth)
            messageLabel.displayMessage("People occlusion on", duration: 1.0)
        }
        arView.session.run(config)
    }

Interpretation

Observed: the app never creates an ARWorldTrackingConfiguration. It reads the one RealityKit installed on arView.session and returns early when there is none yet (PeopleOcclusion/ViewController.swift:47). The toggle is attempted once from viewDidAppear(_:) (PeopleOcclusion/ViewController.swift:36) and again on every tap (PeopleOcclusion/ViewController.swift:40).

Inference: relying on ARView’s automatic session configuration keeps the sample to a few lines, but it makes the initial state timing-dependent. If the session is not configured when the view appears, occlusion starts off and the first tap turns it on.

Ownership and state

Ownership evidence

PeopleOcclusion/ViewController.swift:14 — outlets supplied by the storyboard; the model is created and attached in viewDidLoad

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!
    @IBOutlet var messageLabel: RoundedLabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        do {
            let vase = try ModelEntity.load(named: "vase")
            
            // Place model on a horizontal plane.
            let anchor = AnchorEntity(plane: .horizontal, minimumBounds: [0.15, 0.15])
            arView.scene.anchors.append(anchor)
            
            vase.scale = [1, 1, 1] * 0.006
            anchor.children.append(vase)
        } catch {
            fatalError("Failed to load asset.")
        }
    }
    // ...
}
Owner Object or state Relationship Mutation authority
Storyboard ARView, RoundedLabel, ARCoachingOverlayView, tap recognizer Instantiated by Interface Builder and connected to ViewController outlets and actions (PeopleOcclusion/Base.lproj/Main.storyboard:55, PeopleOcclusion/Base.lproj/Main.storyboard:56) —
ViewController arView, messageLabel Implicitly unwrapped @IBOutlet var (strong by default) Only ViewController uses them
ARView.scene AnchorEntity with the vase as a child Created locally in viewDidLoad and appended to the scene, which retains it ViewController adds it once
ARView.session Current ARWorldTrackingConfiguration Created by RealityKit; read and re-run by ViewController togglePeopleOcclusion()
RoundedLabel tag as a message generation counter Inherited UIView.tag repurposed (PeopleOcclusion/RoundedLabel.swift:25) displayMessage(_:duration:)
SceneDelegate window Stored var (PeopleOcclusion/SceneDelegate.swift:12); the scene manifest’s storyboard supplies the window, and scene(_:willConnectTo:options:) only checks the scene type UIKit

Concurrency, scheduling, and thread safety

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

Concern Source mechanism Verified placement or handoff Evidence
UIKit callbacks viewDidLoad, viewDidAppear(_:), @IBAction onTap(_:) Model setup and occlusion toggling run from view-controller lifecycle and gesture callbacks. PeopleOcclusion/ViewController.swift:17, PeopleOcclusion/ViewController.swift:34, PeopleOcclusion/ViewController.swift:39
Main-queue scheduling DispatchQueue.main.async Shows the label and sets its text. PeopleOcclusion/RoundedLabel.swift:19
Delayed main-queue scheduling DispatchQueue.main.asyncAfter Hides the label after duration unless a newer message changed tag. PeopleOcclusion/RoundedLabel.swift:28
Shared-state safety tag comparison tag is incremented in the caller’s context (PeopleOcclusion/RoundedLabel.swift:26), while the comparison runs in the main-queue block. All callers in this sample are UIKit main-thread callbacks; no other synchronization is present. PeopleOcclusion/RoundedLabel.swift:30

No Swift concurrency, actor, task, or Combine appears. The project sets no default actor isolation.

Reference code

PeopleOcclusion/RoundedLabel.swift:18 — a generation counter suppresses stale hide work

    func displayMessage(_ text: String, duration: TimeInterval) {
        DispatchQueue.main.async {
            self.isHidden = false
            self.text = text
        }
        
        // Use 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 showMessage is called again before this block kicks in.
            if self.tag == tag {
                self.isHidden = true
            }
        }
    }

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
Event delivery Target-action (UITapGestureRecognizer → onTap:) Each tap toggles occlusion PeopleOcclusion/Base.lproj/Main.storyboard:62, PeopleOcclusion/ViewController.swift:39
Event delivery UIKit lifecycle delegates AppDelegate supplies the scene configuration; SceneDelegate receives scene callbacks PeopleOcclusion/AppDelegate.swift:38, PeopleOcclusion/SceneDelegate.swift:14
State propagation Direct mutation of the session configuration frameSemantics insert/remove followed by session.run(config) PeopleOcclusion/ViewController.swift:56, PeopleOcclusion/ViewController.swift:59
Interface Builder wiring Coaching overlay sessionProvider and delegate outlets The overlay observes the ARView’s session; its delegate outlet targets ViewController, which implements no coaching-overlay delegate methods in Swift PeopleOcclusion/Base.lproj/Main.storyboard:38, PeopleOcclusion/Base.lproj/Main.storyboard:39
Swift module import UIKit, RealityKit, ARKit Views, ARView/entities, configuration and frame semantics PeopleOcclusion/ViewController.swift:8, PeopleOcclusion/ViewController.swift:9, PeopleOcclusion/ViewController.swift:10
Privacy declaration NSCameraUsageDescription Camera access string PeopleOcclusion/Info.plist:23

Class and protocol design

Reference code

PeopleOcclusion/AppDelegate.swift:38 — the application delegate hands UIKit the scene configuration named in Info.plist

    func application(_ application: UIApplication,
                     configurationForConnecting connectingSceneSession: UISceneSession,
                     options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
Type Responsibility Depends on
AppDelegate @UIApplicationMain entry; returns the default scene configuration; other lifecycle methods are empty UIKit
SceneDelegate Holds the window; scene callbacks are empty apart from a type check UIKit
ViewController Loads and anchors the model; toggles people occlusion; shows feedback ARView, ARWorldTrackingConfiguration, RoundedLabel
RoundedLabel Inset text drawing and transient messages UILabel

The sample declares no local protocol. Its only protocol conformances are UIKit lifecycle delegates.

Access control

Symbol Access Verified effect Likely rationale
ViewController.togglePeopleOcclusion() fileprivate Callable only from ViewController.swift (PeopleOcclusion/ViewController.swift:43). Inference: the toggle is an implementation detail reached through lifecycle and tap callbacks only.
ViewController.arView, messageLabel implicitly internal @IBOutlet var Interface Builder can connect them; other module code could also reach them (PeopleOcclusion/ViewController.swift:14, PeopleOcclusion/ViewController.swift:15). Inference: the storyboard sets propertyAccessControl="none", so outlets follow the default access level.
RoundedLabel.displayMessage(_:duration:) implicitly internal The view controller calls it (PeopleOcclusion/RoundedLabel.swift:18). —
AppDelegate.window, SceneDelegate.window implicitly internal UIKit-facing stored properties (PeopleOcclusion/AppDelegate.swift:13, PeopleOcclusion/SceneDelegate.swift:12). —

Nothing is private, public, or open.

Reference code

PeopleOcclusion/ViewController.swift:39 — the internal IB action forwards to the file-private toggle

    @IBAction func onTap(_ sender: UITapGestureRecognizer) {
        togglePeopleOcclusion()
    }

Logic ownership and placement

Logic Owning type or file Placement rationale
Model loading and plane anchoring ViewController.viewDidLoad() Observed: synchronous ModelEntity.load(named:) and an AnchorEntity(plane:minimumBounds:) (PeopleOcclusion/ViewController.swift:21, PeopleOcclusion/ViewController.swift:24).
Capability check and occlusion toggle ViewController.togglePeopleOcclusion() Observed: supportsFrameSemantics(.personSegmentationWithDepth) precedes the toggle and is fatal when unsupported (PeopleOcclusion/ViewController.swift:48).
User guidance while tracking initializes ARCoachingOverlayView in the storyboard Observed: no Swift code; configured only through outlets.
Transient feedback RoundedLabel.displayMessage(_:duration:) Observed: show, then hide after a delay unless superseded.
Scene lifecycle AppDelegate + SceneDelegate + Info.plist Observed: the manifest names the delegate and storyboard; the code only returns the configuration.

Design patterns

Pattern Source evidence Purpose or tradeoff
Delegate or data-source callbacks PeopleOcclusion/AppDelegate.swift:11, PeopleOcclusion/AppDelegate.swift:38, PeopleOcclusion/SceneDelegate.swift:10 UIKit calls the application and scene delegates for lifecycle events; the app answers only the scene-configuration request.

The sample uses one storyboard-instantiated view controller as the only feature owner. That is the whole app, so no broader view-controller organization or architecture label is claimed.

Naming conventions

  • Types use UIKit role names: AppDelegate, SceneDelegate, ViewController. RoundedLabel names its visual trait.
  • Outlets are named for the view they hold (arView, messageLabel); the IB action uses the on… prefix (onTap(_:)).
  • The feature method is a verb phrase naming the toggled capability (togglePeopleOcclusion()).
  • The scene configuration name string "Default Configuration" matches the UISceneConfigurationName in Info.plist.

Architecture takeaways

  • For a single framework feature, edit the live configuration (session.configuration) and re-run it, rather than rebuilding session setup.
  • When a framework configures a session for you, guard against reading it before it exists, and decide which user action will apply the change once it does.
  • Check device support with supportsFrameSemantics(_:) before turning a frame semantic on.
  • Interface Builder can own most wiring (outlets, a coaching overlay’s session provider, a tap action), leaving the controller with only the feature logic.
  • A small generation counter is enough to stop delayed UI work from undoing a newer message.

Source map

Source file Relevant symbols
PeopleOcclusion/AppDelegate.swift AppDelegate, application(_:configurationForConnecting:options:)
PeopleOcclusion/SceneDelegate.swift SceneDelegate, window
PeopleOcclusion/ViewController.swift ViewController, viewDidLoad(), onTap(_:), togglePeopleOcclusion()
PeopleOcclusion/RoundedLabel.swift RoundedLabel, displayMessage(_:duration:)
PeopleOcclusion/Base.lproj/Main.storyboard ARView, ARCoachingOverlayView, outlets, tap action
PeopleOcclusion/Info.plist Scene manifest, NSCameraUsageDescription, arkit capability
PeopleOcclusion.xcodeproj/project.pbxproj Target, deployment target, vase.usdz resource