Building a custom peer-to-peer protocol
At a glance
| Item | Summary |
|---|---|
| Purpose | Use networking frameworks to create a custom protocol for playing a game across iOS, iPadOS, watchOS, and tvOS devices. |
| App architecture | A Swift sample with the source-visible chain AppDelegate → GameViewController → Network APIs. |
| Main patterns | View-controller organization, Protocol-oriented abstraction, Delegate or data-source callbacks |
| Project style | 18 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries. |
Project structure
Source bundle/
└── TicTacToe/
├── TicTacToe-iOS/
│ ├── AppDelegate.swift
│ └── Views/
│ ├── GameViewController.swift
│ ├── PeerListViewController.swift
│ ├── GameScene.swift
│ └── PasscodeViewController.swift
├── TicTacToe-tvOS/
│ ├── AppDelegate.swift
│ └── Views/
│ ├── GameViewController.swift
│ ├── PeerListViewController.swift
│ └── GameScene.swift
└── TicTacToe-watchOS Extension/
├── GameViewController.swift
├── ExtensionDelegate.swift
└── GameScene.swift
Structure observations
- Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
- Primary languages: Swift.
- The verified tree contains 11 project/configuration file(s) and 30 source declaration(s).
Overall architecture
flowchart LR
N1["AppDelegate"]
N2["GameViewController"]
N3["Network APIs"]
N1 --> N2
N2 --> N3
Reference code
TicTacToe/TicTacToe-iOS/AppDelegate.swift:10 — architecture anchor
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}Interpretation
The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into Network.
Ownership and state
classDiagram
AppDelegate o-- UIWindow : window
GameViewController o-- SKView : sceneView
GameViewController o-- UILabel : instructionLabel
GameViewController o-- UIButton : leftButton
Ownership evidence
TicTacToe/TicTacToe-iOS/AppDelegate.swift:12 — stored dependency or nearest verified ownership anchor
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
AppDelegate |
UIWindow (window) |
stores or receives | App/module collaborators |
GameViewController |
SKView (sceneView) |
holds a non-owning reference | The referenced object’s lifecycle is owned elsewhere |
GameViewController |
UILabel (instructionLabel) |
holds a non-owning reference | The referenced object’s lifecycle is owned elsewhere |
GameViewController |
UIButton (leftButton) |
holds a non-owning reference | The referenced object’s lifecycle is owned elsewhere |
Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.
Class and protocol design
TicTacToe/Networking/PeerBrowser.swift:13 — representative type boundary
protocol PeerBrowserDelegate: AnyObject {
func refreshResults(results: Set<NWBrowser.Result>)
func displayBrowseError(_ error: NWError)
}| Type | Responsibility | Depends on or conforms to |
|---|---|---|
AppDelegate |
Receives callback-driven events | UIResponder, UIApplicationDelegate |
AppDelegate |
Receives callback-driven events | UIResponder, UIApplicationDelegate |
PeerBrowserDelegate |
Defines a capability or collaboration contract | AnyObject |
PeerConnectionDelegate |
Defines a capability or collaboration contract | AnyObject |
GameViewController |
View lifecycle, callbacks, and feature coordination | UITableViewController |
GameViewController |
View lifecycle, callbacks, and feature coordination | UITableViewController |
GameViewController |
View lifecycle, callbacks, and feature coordination | WKInterfaceController |
PeerListViewController |
View lifecycle, callbacks, and feature coordination | UITableViewController |
PeerListViewController |
View lifecycle, callbacks, and feature coordination | UITableViewController |
GameScene |
Scene lifecycle or scene-level composition | SKScene |
The source explicitly defines local protocol relationships: GameViewController → PeerConnectionDelegate, PeerListViewController → PeerBrowserDelegate, PeerListViewController → PeerConnectionDelegate, GameViewController → PeerConnectionDelegate, PeerListViewController → PeerConnectionDelegate, GameViewController → PeerConnectionDelegate.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
tlsOptions (TicTacToe/Networking/NWParameters+InitWithPasscode.swift:32) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: hide an implementation step that is not part of the collaboration surface. |
stringToDispatchData (TicTacToe/Networking/NWParameters+InitWithPasscode.swift:51) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: hide an implementation step that is not part of the collaboration surface. |
boardLabels (TicTacToe/TicTacToe-iOS/Views/GameScene.swift:13) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
boardSquares (TicTacToe/TicTacToe-iOS/Views/GameScene.swift:14) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
Reference code
TicTacToe/Networking/NWParameters+InitWithPasscode.swift:32 — representative boundary
private static func tlsOptions(passcode: String) -> NWProtocolTLS.Options {
// ...
}Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| View lifecycle, callbacks, and feature coordination | GameViewController, PasscodeViewController, PeerListViewController |
The source’s Controller suffix makes this role explicit. |
| Receives callback-driven events | AppDelegate, ExtensionDelegate, PeerBrowserDelegate, PeerConnectionDelegate |
The source’s Delegate suffix makes this role explicit. |
| Scene lifecycle or scene-level composition | GameScene |
The source’s Scene suffix makes this role explicit. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | TicTacToe/TicTacToe-iOS/Views/GameViewController.swift:42 |
A controller is the verified coordination boundary; this is MVC-style only where a separate model is present. |
| Protocol-oriented abstraction | TicTacToe/TicTacToe-iOS/Views/GameViewController.swift:240 |
A local protocol and concrete conformance create an explicit capability boundary. |
| Delegate or data-source callbacks | TicTacToe/TicTacToe-iOS/AppDelegate.swift:11 |
Callback protocols invert event delivery back into the sample’s owner. |
Main application flow
Receiving one peer move passes framed Network content through the connection delegate into game state, while the receive callback immediately arms the next message.
sequenceDiagram
participant Peer as Remote peer
participant Network as NWConnection
participant Connection as PeerConnection
participant Controller as GameViewController
participant Scene as GameScene
Peer->>Network: Send framed move
Network-->>Connection: receiveMessage callback
Connection-->>Controller: receivedMessage(content, metadata)
Controller->>Controller: Decode move and validate row/column
Controller->>Scene: placeCharacter(...)
Connection->>Network: receiveNextMessage()
loop until an error occurs
Network-->>Connection: Next framed message callback
end
Reference code
TicTacToe/Networking/PeerConnection.swift:155 — the callback forwards decoded metadata to the delegate and recursively schedules the next receive.
func receiveNextMessage() {
guard let connection = connection else { return }
connection.receiveMessage { (content, context, isComplete, error) in
if let gameMessage = context?.protocolMetadata(definition: GameProtocol.definition) as? NWProtocolFramer.Message {
self.delegate?.receivedMessage(content: content, message: gameMessage)
}
if error == nil {
self.receiveNextMessage()
}
}
}TicTacToe/TicTacToe-iOS/Views/GameViewController.swift:252 — the delegate dispatches a move and applies validated coordinates to the scene.
func receivedMessage(content: Data?, message: NWProtocolFramer.Message) {
guard let content = content else { return }
switch message.gameMessageType {
case .invalid:
print("Received invalid message")
case .selectedCharacter:
handleSelectCharacter(content, message)
case .move:
handleMove(content, message)
}
}Naming conventions
- Types: Controller: GameViewController, PasscodeViewController, PeerListViewController; Delegate: AppDelegate, ExtensionDelegate, PeerBrowserDelegate, PeerConnectionDelegate; Scene: GameScene.
- Protocols:
PeerBrowserDelegate,PeerConnectionDelegate. - Methods:
emojiArray,hideButtons,disableButtons,enableButtons,declareWinner,handleMyTurnSelectFamily,handleWaitingToSelectFamily,handleMyTurn. - Files:
TicTacToe/TicTacToe-iOS/AppDelegate.swift,TicTacToe/TicTacToe-tvOS/AppDelegate.swift,TicTacToe/TicTacToe-iOS/Views/GameViewController.swift,TicTacToe/TicTacToe-tvOS/Views/GameViewController.swift,TicTacToe/TicTacToe-watchOS Extension/GameViewController.swift,TicTacToe/TicTacToe-iOS/Views/PeerListViewController.swift.
Architecture takeaways
AppDelegateis the main source-visible entry or composition anchor for this sample.- Framework work reaches Network, UIKit, SpriteKit, GameplayKit through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
- Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
- Access-control conclusions separate verified language visibility from the likely design rationale.
- Local protocol relationships provide an explicit substitution boundary.
Source map
| Source file | Relevant symbols |
|---|---|
TicTacToe/TicTacToe-iOS/AppDelegate.swift |
AppDelegate |
TicTacToe/TicTacToe-tvOS/AppDelegate.swift |
AppDelegate |
TicTacToe/TicTacToe-iOS/Views/GameViewController.swift |
GameCharacterFamily, GameResult, GameViewController |
TicTacToe/TicTacToe-tvOS/Views/GameViewController.swift |
GameCharacterFamily, GameResult, GameViewController |
TicTacToe/TicTacToe-watchOS Extension/GameViewController.swift |
GameCharacterFamily, GameResult, GameViewController |
TicTacToe/TicTacToe-iOS/Views/PeerListViewController.swift |
PeerListViewController, GameFinderSection |
TicTacToe/TicTacToe-tvOS/Views/PeerListViewController.swift |
PeerListViewController, GameFinderSection |
TicTacToe/TicTacToe-iOS/Views/GameScene.swift |
GameScene |
TicTacToe/TicTacToe-iOS/Views/PasscodeViewController.swift |
PasscodeViewController |
TicTacToe/TicTacToe-tvOS/Views/GameScene.swift |
GameScene |
TicTacToe/Networking/PeerConnection.swift |
PeerConnection, PeerConnectionDelegate, receive loop |