Drawing content in a group session
At a glance
| Item | Summary |
|---|---|
| Purpose | Share a drawing canvas and placed photos with FaceTime participants through a SharePlay GroupSession. |
| App architecture | A single SwiftUI app target. ContentView creates one @MainActor Canvas object, passes it to three child views, and feeds it each incoming GroupSession. Canvas owns the session’s messenger, journal, Combine subscriptions, and listener tasks. |
| Main patterns | Publisher-backed observable state, Message-based session synchronization |
| Project style | One target with Model/ and View/ folders; one primary type per file. |
| Execution model | Canvas is @MainActor. Three retained listener Tasks iterate async sequences and are cancelled in reset(). Several fire-and-forget Tasks handle sends and activation. A withTaskGroup fan-out loads journal attachments. SwiftUI .task drives the session sequence. No Task.detached or dispatch queues. |
| State/event model | ObservableObject/@Published on Canvas and on each Stroke; Combine sink on GroupSession publishers; for await over GroupSessionMessenger and GroupSessionJournal sequences. |
| Key frameworks/packages | SwiftUI, GroupActivities, Combine, PhotosUI, and Foundation imports. No Swift package manifest. |
Platform note: the catalog lists iOS, iPadOS, and Mac Catalyst. The project file sets TARGETED_DEVICE_FAMILY = "1,2" (iPhone and iPad) and IPHONEOS_DEPLOYMENT_TARGET = 17.0, and shows no explicit Mac Catalyst setting (DrawTogether.xcodeproj/project.pbxproj:371, DrawTogether.xcodeproj/project.pbxproj:361).
Project structure
Drawing content in a group session/
├── Configuration/SampleCode.xcconfig
├── DrawTogether.xcodeproj one application target
└── DrawTogether/
├── DrawTogetherApp.swift @main, WindowGroup { ContentView() }
├── DrawTogether.entitlements com.apple.developer.group-session
├── Model/
│ ├── DrawTogether.swift GroupActivity definition
│ ├── Canvas.swift @MainActor session and canvas state owner
│ ├── Stroke.swift observable, Codable stroke + Color enum
│ └── Messages.swift Codable wire messages
└── View/
├── ContentView.swift owns Canvas, observes sessions()
├── CanvasView.swift renders strokes and images, drag gesture
├── PhotoPlacementView.swift drag and long-press to place a photo
├── ControlBar.swift share, photo picker, reset
├── StrokeView.swift renders one Stroke
└── StrokeColorIndicator.swift local color swatch
Structure observations
- The split is folder-based (
Model/,View/), not target-based. The project has onecom.apple.product-type.applicationtarget (DrawTogether.xcodeproj/project.pbxproj:156). Model/separates three concerns: the activity type (DrawTogether), the wire protocol (Messages.swift), and the stateful owner (Canvas).Strokeis both observable view state and a wire payload insideCanvasMessage.- Every view except
StrokeColorIndicatortakesCanvasorStrokethrough an initializer parameter. No view uses the SwiftUI environment for the model.
Overall architecture
flowchart LR
App["DrawTogetherApp"] --> Content["ContentView (@StateObject canvas)"]
Content --> Views["CanvasView / PhotoPlacementView / ControlBar"]
Views -- intents --> Canvas["Canvas (@MainActor)"]
Content -- "for await DrawTogether.sessions()" --> Canvas
Canvas --> Session["GroupSession<DrawTogether>"]
Canvas --> Messenger["GroupSessionMessenger"]
Canvas --> Journal["GroupSessionJournal"]
Messenger -- "messages(of:)" --> Canvas
Journal -- attachments --> Canvas
Reference code
DrawTogether/View/ContentView.swift:11 — ContentView
struct ContentView: View {
@StateObject var canvas = Canvas()
var body: some View {
VStack {
// ...
ZStack {
CanvasView(canvas: canvas)
PhotoPlacementView(canvas: canvas)
}
ControlBar(canvas: canvas)
.padding()
}
.task {
for await session in DrawTogether.sessions() {
canvas.configureGroupSession(session)
}
}
}
}Interpretation
Observed: Canvas is the only stateful collaborator. Views send intents to it (addPointToActiveStroke, finishStroke, finishImagePlacement, startSharing, reset) and read its @Published properties. GroupActivities objects reach Canvas in two ways: ContentView forwards each session from DrawTogether.sessions(), and Canvas then consumes the messenger and journal sequences itself.
Inference: Canvas combines the roles of local drawing model and session-synchronization controller. The sample has no separate view-model or service layer.
Ownership and state
classDiagram
ContentView *-- Canvas : StateObject
ControlBar *-- GroupStateObserver : StateObject
CanvasView o-- Canvas : ObservedObject
PhotoPlacementView o-- Canvas : ObservedObject
ControlBar o-- Canvas : ObservedObject
Canvas *-- GroupSessionMessenger : creates
Canvas *-- GroupSessionJournal : creates
Canvas o-- GroupSession : configureGroupSession
Canvas *-- Stroke : creates
StrokeView o-- Stroke : ObservedObject
Ownership evidence
DrawTogether/Model/Canvas.swift:105 — configureGroupSession(_:)
func configureGroupSession(_ groupSession: GroupSession<DrawTogether>) {
strokes = []
self.groupSession = groupSession
let messenger = GroupSessionMessenger(session: groupSession)
self.messenger = messenger
let journal = GroupSessionJournal(session: groupSession)
self.journal = journal
// ...
groupSession.join()
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
ContentView |
Canvas |
Creates and retains it with @StateObject (DrawTogether/View/ContentView.swift:12) |
Canvas methods. Views also assign canvas.selectedImageData directly (DrawTogether/View/ControlBar.swift:43). |
CanvasView, PhotoPlacementView, ControlBar |
Canvas |
Receive it from ContentView as @ObservedObject (DrawTogether/View/CanvasView.swift:11) |
Canvas |
ControlBar |
GroupStateObserver |
Creates it with @StateObject and reads isEligibleForGroupSession (DrawTogether/View/ControlBar.swift:14, DrawTogether/View/ControlBar.swift:19) |
GroupActivities framework |
ControlBar |
selectedItem: PhotosPickerItem? |
@State private, bound to PhotosPicker (DrawTogether/View/ControlBar.swift:15) |
ControlBar |
PhotoPlacementView |
location: CGPoint |
@State private, updated by drag (DrawTogether/View/PhotoPlacementView.swift:13) |
PhotoPlacementView |
Canvas |
strokes, activeStroke, images, selectedImageData, groupSession |
@Published (DrawTogether/Model/Canvas.swift:21, DrawTogether/Model/Canvas.swift:91) |
Canvas (and ControlBar for selectedImageData) |
Canvas |
messenger, journal |
Creates them per session and stores them (DrawTogether/Model/Canvas.swift:109) |
configureGroupSession sets them; reset clears them |
Canvas |
subscriptions: Set<AnyCancellable>, tasks: Set<Task<Void, Never>> |
Retains Combine and task lifetimes (DrawTogether/Model/Canvas.swift:27) |
configureGroupSession inserts; reset cancels and clears |
Canvas |
Stroke instances |
Creates them locally (DrawTogether/Model/Canvas.swift:35) or from remote messages (DrawTogether/Model/Canvas.swift:161) |
Canvas appends to stroke.points |
StrokeView |
Stroke |
@ObservedObject (DrawTogether/View/StrokeView.swift:11) |
Canvas |
Observed: appending a point mutates stroke.points, which is @Published on Stroke (DrawTogether/Model/Stroke.swift:13). It does not reassign Canvas.strokes, so each StrokeView observes its own stroke for incremental redraws.
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.
Build setting: SWIFT_VERSION = 5.0, and the project file contains no strict-concurrency setting (DrawTogether.xcodeproj/project.pbxproj:370).
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Main-actor isolation | @MainActor class Canvas |
All Canvas properties and methods are main-actor isolated, including the tasks and subscriptions sets and the handle(_:) overloads. |
DrawTogether/Model/Canvas.swift:19 |
| Retained listener tasks | Three plain Task {}s, each stored with tasks.insert(task) |
Each loops for await over messenger.messages(of: UpsertStrokeMessage.self), messenger.messages(of: CanvasMessage.self), or journal.attachments. The tasks are created inside a main-actor method, so their bodies inherit main-actor context and call handle(_:) without await. |
DrawTogether/Model/Canvas.swift:133, DrawTogether/Model/Canvas.swift:138, DrawTogether/Model/Canvas.swift:148 |
| Cancellation | tasks.forEach { $0.cancel() }, subscriptions = [] |
reset() cancels all listener tasks and releases the Combine subscriptions. It also clears the messenger and journal, leaves the session, and restarts sharing if a session existed. |
DrawTogether/Model/Canvas.swift:77, DrawTogether/Model/Canvas.swift:79 |
| Fire-and-forget sends | Plain Task {} around try? await messenger.send(...) |
Each drag point sends an UpsertStrokeMessage. New participants receive a CanvasMessage addressed .only(newParticipants). Handles are not stored, and try? discards send errors. |
DrawTogether/Model/Canvas.swift:42, DrawTogether/Model/Canvas.swift:127 |
| Prioritized upload | Task(priority: .userInitiated) |
Adds the selected photo to the journal with location metadata. The handle is not stored, and a thrown error ends the task silently. | DrawTogether/Model/Canvas.swift:62 |
| Activation | Plain Task {} in startSharing() |
Awaits DrawTogether().activate() and prints any error. The handle is not stored. |
DrawTogether/Model/Canvas.swift:96 |
| Structured fan-out | withTaskGroup(of: CanvasImage?.self) + group.addTask |
For each journal attachment, a child task awaits loadMetadata(of:) and load(Data.self). The parent collects results in completion order and assigns self.images once. The source does not establish the child tasks’ executor. |
DrawTogether/Model/Canvas.swift:174, DrawTogether/Model/Canvas.swift:178 |
| View-lifetime task | SwiftUI .task { for await session in DrawTogether.sessions() } |
The source does not store this task. SwiftUI’s .task modifier owns its lifetime (framework behavior, not visible in source). |
DrawTogether/View/ContentView.swift:31 |
| View-originated task | Plain Task {} in .onChange(of: selectedItem) |
Awaits loadTransferable(type: Data.self) and then assigns canvas.selectedImageData. The source does not annotate the closure’s actor; the handle is not stored. |
DrawTogether/View/ControlBar.swift:40 |
| Combine delivery | groupSession.$state.sink, groupSession.$activeParticipants.sink |
Subscriptions are stored in subscriptions. No receive(on:) or subscribe(on:) is applied, so the source does not establish the delivery context. |
DrawTogether/Model/Canvas.swift:114, DrawTogether/Model/Canvas.swift:123 |
Not present: Task.detached, DispatchQueue, locks, custom actor types, nonisolated, or explicit Sendable conformances. Stroke is a non-isolated class; in source, only main-actor Canvas code mutates its points.
Reference code
DrawTogether/Model/Canvas.swift:69 — reset(): the single cancellation point for session-scoped work
func reset() {
// Clear the local drawing canvas.
strokes = []
images = []
// Tear down the existing groupSession.
messenger = nil
journal = nil
tasks.forEach { $0.cancel() }
tasks = []
subscriptions = []
if groupSession != nil {
groupSession?.leave()
groupSession = nil
self.startSharing()
}
}DrawTogether/Model/Canvas.swift:172 — handle(_:) for journal attachments
func handle(_ attachments: GroupSessionJournal.Attachments.Element) async {
// Ensure that the canvas always has all the images from this sequence.
self.images = await withTaskGroup(of: CanvasImage?.self) { group in
var images = [CanvasImage]()
attachments.forEach { attachment in
group.addTask {
do {
let metadata = try await attachment.loadMetadata(of: ImageMetadataMessage.self)
let imageData = try await attachment.load(Data.self)
return .init(id: attachment.id, location: metadata.location, imageData: imageData)
} catch { return nil }
}
}
for await image in group {
if let image {
images.append(image)
}
}
return images
}
}Observed lifetime detail: the sink closures reference self strongly (self.groupSession = nil, self.strokes), and Canvas stores those subscriptions. The listener tasks likewise capture self implicitly. Inference: each session’s subscriptions and tasks keep Canvas alive until reset() clears them. reset() runs on the trash button or when the $state sink sees .invalidated. Because ContentView owns Canvas for the app’s lifetime, this has no visible effect here.
Observed: configureGroupSession does not cancel tasks from an earlier session before it inserts new ones. Cleanup depends on reset() having run, which the .invalidated sink triggers.
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 | @Published on Canvas |
strokes, activeStroke, images, selectedImageData, and groupSession drive SwiftUI re-rendering. |
DrawTogether/Model/Canvas.swift:21 |
| State propagation | @Published var points on Stroke |
Per-stroke observation by StrokeView. |
DrawTogether/Model/Stroke.swift:13 |
| State propagation | Initializer injection of @ObservedObject |
ContentView passes the same Canvas to each child view. |
DrawTogether/View/ContentView.swift:23 |
| State propagation | Binding ($selectedItem) |
PhotosPicker writes the picked item into ControlBar state. |
DrawTogether/View/ControlBar.swift:32 |
| Network ingress | for await over messenger.messages(of:) and journal.attachments |
Remote messages and attachments mutate Canvas through the handle(_:) overloads. |
DrawTogether/Model/Canvas.swift:134 |
| Network egress | messenger.send(_:), messenger.send(_:to:), journal.add(_:metadata:) |
Local edits are broadcast as typed Codable values. |
DrawTogether/Model/Canvas.swift:43, DrawTogether/Model/Canvas.swift:63 |
| Combine scheduling | None (sink without receive(on:) or subscribe(on:)) |
The source does not set delivery or subscription scheduling. | DrawTogether/Model/Canvas.swift:115 |
| Framework import | Combine, GroupActivities |
Compilation dependencies of Canvas.swift. |
DrawTogether/Model/Canvas.swift:9, DrawTogether/Model/Canvas.swift:11 |
| Framework import | PhotosUI |
Compilation dependency of ControlBar (PhotosPicker). |
DrawTogether/View/ControlBar.swift:10 |
| Framework import | SwiftUI |
App entry and views. | DrawTogether/DrawTogetherApp.swift:8 |
| Package declaration | None | No Package.swift in the bundle; system frameworks only. |
DrawTogether.xcodeproj/project.pbxproj:156 |
The app target’s entitlements file enables com.apple.developer.group-session.
Class and protocol design
classDiagram
class GroupActivity {
<<protocol>>
}
DrawTogether ..|> GroupActivity
Canvas ..|> ObservableObject
Stroke ..|> ObservableObject
Stroke ..|> Codable
UpsertStrokeMessage ..|> Codable
CanvasMessage ..|> Codable
ImageMetadataMessage ..|> Codable
CanvasMessage --> Stroke
Reference code
DrawTogether/Model/Messages.swift:11 — wire messages
struct UpsertStrokeMessage: Codable {
let id: UUID
let color: Stroke.Color
let point: CGPoint
}
struct CanvasMessage: Codable {
let strokes: [Stroke]
let pointCount: Int
}
struct ImageMetadataMessage: Codable {
let location: CGPoint
}| Type | Responsibility | Depends on |
|---|---|---|
DrawTogether |
GroupActivity with metadata title and .generic type (DrawTogether/Model/DrawTogether.swift:11) |
GroupActivities |
Canvas |
Local drawing state, session setup and teardown, send and receive | GroupSession, GroupSessionMessenger, GroupSessionJournal, Stroke |
Stroke |
Observable point list, color, and Path; custom Codable because @Published is not automatically coded (DrawTogether/Model/Stroke.swift:41) |
SwiftUI.Path |
Stroke.Color |
Int-backed Codable, CaseIterable palette with a random pick (DrawTogether/Model/Stroke.swift:57) |
SwiftUI.Color |
CanvasImage |
Identifiable value for a placed photo (DrawTogether/Model/Canvas.swift:13) |
Foundation |
UpsertStrokeMessage, CanvasMessage, ImageMetadataMessage |
Typed incremental, full-state, and attachment-metadata payloads | Stroke, CGPoint |
CanvasView, PhotoPlacementView, ControlBar |
Gesture and button input that forwards to Canvas |
Canvas |
No local protocol is declared; the design uses concrete types throughout.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
selectedItem (DrawTogether/View/ControlBar.swift:15) |
@State private |
Only ControlBar can read or write the picker selection. |
Inference: picker state is a local UI concern. |
location (DrawTogether/View/PhotoPlacementView.swift:13) |
@State private |
Only PhotoPlacementView moves the preview. |
Inference: drag position is committed only on long press. |
Canvas members (DrawTogether/Model/Canvas.swift:27) |
implicit internal |
subscriptions, tasks, messenger, journal, and every @Published property can be read and written from any file in the module. ControlBar writes selectedImageData directly. |
Inference: sample brevity. No private(set) restricts which code can write Canvas state. |
Stroke.points (DrawTogether/Model/Stroke.swift:13) |
implicit internal |
Canvas appends to it from outside the Stroke type. |
Inference: the stroke acts as a mutable record. |
Reference code
DrawTogether/Model/Canvas.swift:19 — Canvas stored state (all implicitly internal)
@MainActor
class Canvas: ObservableObject {
@Published var strokes = [Stroke]()
@Published var activeStroke: Stroke?
@Published var images = [CanvasImage]()
@Published var selectedImageData: Data?
let strokeColor = Stroke.Color.random
var subscriptions = Set<AnyCancellable>()
var tasks = Set<Task<Void, Never>>()
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Gesture to stroke point | CanvasView.strokeGesture → Canvas.addPointToActiveStroke (DrawTogether/View/CanvasView.swift:37) |
The view translates gestures; the model owns the stroke state. |
| Incremental remote upsert | Canvas.handle(_: UpsertStrokeMessage) (DrawTogether/Model/Canvas.swift:157) |
Finds a stroke by id or creates one, then appends the point. |
| Late-joiner catch-up | $activeParticipants sink → CanvasMessage to .only(newParticipants) (DrawTogether/Model/Canvas.swift:123) |
Full state goes only to new participants. newParticipants is computed by subtracting the session’s current activeParticipants from the published value. Inference: this relies on @Published emitting before the stored value changes. |
| Full-state conflict rule | Canvas.handle(_: CanvasMessage) (DrawTogether/Model/Canvas.swift:168) |
Accepts a snapshot only if its pointCount exceeds the local count. This is a simple “most points wins” merge. |
| Photo sharing | Canvas.finishImagePlacement → journal.add; journal.attachments → handle(_:) (DrawTogether/Model/Canvas.swift:57) |
Large binary data goes through the journal, not the messenger. The local image appears only when the journal’s attachment sequence delivers it. |
| Session lifecycle | Canvas.configureGroupSession / reset / startSharing |
One owner sets up and tears down everything session-scoped. |
| Share-button eligibility | ControlBar with GroupStateObserver (DrawTogether/View/ControlBar.swift:19) |
A UI-only decision placed in the view. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Publisher-backed observable state | DrawTogether/Model/Canvas.swift:21 Canvas; DrawTogether/Model/Stroke.swift:13 Stroke.points |
Two observation levels: canvas-wide collections and per-stroke points. Tradeoff: the properties are internal var, so any file in the module can write them. |
| Message-based session synchronization | DrawTogether/Model/Messages.swift:11; send at DrawTogether/Model/Canvas.swift:43; receive loops at DrawTogether/Model/Canvas.swift:133 |
Participants exchange typed Codable messages: small incremental upserts, a full snapshot for late joiners, and journal attachments for images. Each message type has its own for await listener and handle(_:) overload. |
Main application flow
sequenceDiagram
actor User
participant CV as CanvasView
participant C as Canvas (@MainActor)
participant M as GroupSessionMessenger
participant R as Remote Canvas
User->>CV: drag
CV->>C: addPointToActiveStroke(point)
C->>C: stroke.points.append(point)
C->>M: Task { try? await send(UpsertStrokeMessage) }
M-->>R: for await (message, _) in messages(of:)
R->>R: handle(message) → append or create Stroke
Reference code
DrawTogether/Model/Canvas.swift:30 — addPointToActiveStroke(_:)
func addPointToActiveStroke(_ point: CGPoint) {
let stroke: Stroke
if let activeStroke = activeStroke {
stroke = activeStroke
} else {
stroke = Stroke(color: strokeColor)
activeStroke = stroke
}
stroke.points.append(point)
if let messenger = messenger {
Task {
try? await messenger.send(UpsertStrokeMessage(id: stroke.id, color: stroke.color, point: point))
}
}
}Naming conventions
- Types: domain nouns (
Canvas,Stroke,CanvasImage). The activity type is named after the app (DrawTogether). Views use a…Viewsuffix, exceptControlBarandStrokeColorIndicator, which name their UI role. - Messages: a
…Messagesuffix plus intent (UpsertStrokeMessagefor insert-or-append,CanvasMessagefor a full snapshot,ImageMetadataMessagefor attachment metadata). - Methods: intent verbs for UI commands (
addPointToActiveStroke,finishStroke,finishImagePlacement,startSharing,reset).configureGroupSession(_:)performs session setup.handle(_:)is overloaded by message type, which keeps receive logic uniform. - Files: one primary type per file, grouped under
Model/orView/.Canvas.swiftalso declaresCanvasImage, andStroke.swiftnestsStroke.Colorin an extension.
Architecture takeaways
- Put all session-scoped resources (messenger, journal, subscriptions, listener tasks) on one owner, and give that owner a single
reset()that cancels and clears them. RetainingTaskhandles in a set is what makes cancellation possible. - Use one
for awaitloop per message type and overloadhandle(_:). Each typed stream is easy to reason about, and a@MainActorowner lets the handlers mutate UI state without hops. - Separate cheap, frequent updates (per-point upserts) from occasional full snapshots (late joiners) and large binary data (journal attachments).
- Use
withTaskGroupto load independent attachments concurrently and publish the result with a single assignment. - Fire-and-forget
Tasks withtry?keep the sample short but discard send failures. Production code would need an error and retry policy.
Source map
| Source file | Relevant symbols |
|---|---|
DrawTogether/DrawTogetherApp.swift |
DrawTogetherApp |
DrawTogether/Model/Canvas.swift |
CanvasImage, Canvas, subscriptions, tasks, addPointToActiveStroke, finishImagePlacement, reset, startSharing, configureGroupSession, handle(_:) |
DrawTogether/Model/Stroke.swift |
Stroke, points, encode(to:), Stroke.Color |
DrawTogether/Model/Messages.swift |
UpsertStrokeMessage, CanvasMessage, ImageMetadataMessage |
DrawTogether/Model/DrawTogether.swift |
DrawTogether |
DrawTogether/View/ContentView.swift |
ContentView, @StateObject canvas, .task |
DrawTogether/View/CanvasView.swift |
CanvasView, strokeGesture |
DrawTogether/View/ControlBar.swift |
ControlBar, GroupStateObserver, selectedItem, PhotosPicker |
DrawTogether/View/PhotoPlacementView.swift |
PhotoPlacementView, location |
DrawTogether/View/StrokeView.swift |
StrokeView |
DrawTogether.xcodeproj/project.pbxproj |
Application target, IPHONEOS_DEPLOYMENT_TARGET, TARGETED_DEVICE_FAMILY, SWIFT_VERSION |