The HappyOyster iOS SDK entry point is the process-level singleton HappyOysterEngine.shared . Business methods are all async throws , throwing OysterSDKError on failure. A single experience is carried by an OysterTravel handle, spanning three modes — adventure, directing, and acting — on both UIKit and SwiftUI.
Core Concepts
A few terms first, to make the rest of the document easier to read.
Concept | Description |
|---|---|
token | HTTP auth token (Bailian temporary API Key). Your server exchanges it via the Bailian API and delivers it down; it is injected through |
ticket | One-time experience credential. Your server exchanges it via the open platform |
World | An AI world, containing characters and scenes. Created and managed by your server; the SDK is not involved. |
Travel | A single real-time experience, corresponding to one |
Session status |
|
Mode |
|
Overview
After integrating this SDK, your app can enter "worlds" generated in real time by AI, and have a real-time interactive video experience in world exploration mode (adventure), real-time directing mode (directing), or character acting mode (acting): start the experience → real-time playback → real-time interaction → process control (pause/resume/rewind/end) → status and error callbacks.
Each mode supports a different set of capabilities. Drive your UI from the mode returned by start():
Capability | adventure | directing | acting |
|---|---|---|---|
| Yes | No | No |
| No | Yes | Yes |
| No | Yes | Yes |
| No | Yes | No — hide the entry point |
| Yes | Yes | Yes |
| Applied | Ignored | Ignored |
acting worlds are portrait-first: the aspectRatio returned by start() gives the aspect ratio of this experience (9:16 / 16:9); use it to decide the player orientation and container size before pulling the stream (see the "Data Models" section).import HappyOysterSDK; the core entry points are two types.
HappyOysterEngine — the orchestration entry point, a process-level singleton HappyOysterEngine.shared.
Method / Property | Description |
|---|---|
| Initialize the runtime and automatically register the real-time engine (once, before |
| Inject / update the HTTP auth token |
| Create a session handle with a one-time credential |
| Release resources (can |
| Current SDK version |
OysterTravel — the session handle for one experience, created by createTravel(ticket:).
Method / Property | Description |
|---|---|
| Playback view (UIKit / SwiftUI) |
| Status-change + error push stream / observable current status |
| Connect and play (optionally request the maximum duration of a world exploration mode experience) |
| Real-time directing mode text instruction |
| World exploration mode control |
| Pause / resume (supported by |
| Rewind (paused only) |
| End (idempotent, be sure to call) |
| Temporarily yield / restore the microphone |
OysterLog for taking over the SDK's internal logging; HappyOysterEngine.version for reading the version; OysterVideoView is the SwiftUI playback view (equivalent to videoView). Usage is described later in this document.
Lifecycle: initialize → inject token → create session → mount video + subscribe to events → start playback → interact → end. The SDK is not responsible for creating or managing worlds (done by your server), nor does it expose low-level real-time communication details.
Quick Start
A complete flow from initialization to ending, with step-by-step comments. For details of each API, see the "API Reference" section.
Requirements
Item | Requirement |
|---|---|
Minimum OS | iOS 15.0+ (all public types are marked |
Language | Swift ( |
Concurrency | Main-thread access (entry types are marked |
Network | Public network access required |
Permissions |
|
Info.plist must provide NSMicrophoneUsageDescription, otherwise starting real-time capture will crash. When you need exclusive access to the microphone (e.g. for speech recognition), use pauseLocalAudioCapture() / resumeLocalAudioCapture() to temporarily yield and restore it (see the "OysterTravel" section).
Integration and Authentication
Integration and Dependencies
import HappyOysterSDK is all you need at the code level. The SDK is distributed as precompiled binaries (xcframework) via CocoaPods subspecs, published to the public CocoaPods Trunk — declare the dependencies in your Podfile:
AliVCSDK_ARTC is required whenever you pull in HappyOysterSDK/StreamAliRTC: if it is missing, the SDK silently falls back to Loopback — it can connect and reach running, but shows a black screen with no error.Authentication Model
The SDK does not obtain or refresh tokens, staying lightweight. Authentication has two layers, and the integrator manages their lifecycles:
- HTTP auth token (Bailian temporary API Key): Your server exchanges it via the Bailian API and delivers it down; it is injected through
updateToken(_:). Some internal SDK services call the Bailian gateway directly, carrying this token for authentication — therefore it must be a temporary API Key issued by Bailian, not a token from your own business service. The SDK keeps only the latest one, does not persist or refresh it; after it expires, you re-exchange it and inject it again. - One-time experience credential
ticket: Your server exchanges it via the open platformget-travel-credential(prefixtk_, valid for 30 minutes, single-use), used as thecreateTravel(ticket:)argument; it becomes invalid once the experience ends (normally or abnormally) or expires, and cannot be reused.
start / pause / resume / rewind / sendInstruct / sendCommand) are rejected with 108001, and any in-flight experience is actively terminated by the SDK (see the "Error Codes" section); OysterSDKError.raw carries a human-readable reason for the disablement — prompt the user to upgrade when the version is too low.updateToken(_:). There are two places where you need to check whether the token has expired:
- When calling APIs such as
engine.createTravelortravel.start, handle the error and check for the token expired/invalid error types (101001/101002); after injecting the new token, call the corresponding API again. - When listening to the
.errorevent ofOysterTravelEvent, check for the token expired/invalid error types, re-request the token, and inject it.
API Reference
The entry points are two types, both @MainActor and @available(iOS 15.0, *). Business methods are async throws, throwing OysterSDKError on failure; methods with return values are all marked @discardableResult.
HappyOysterEngine
A process-level singleton, the orchestration entry point. init is non-public — always use HappyOysterEngine.shared; do not instantiate it yourself (the underlying real-time engine is also a process-level singleton).
initialize(config:)
Initializes the runtime and automatically registers the real-time engine (no manual registration needed by the host).
When to use: Call once before createTravel, as early as possible after app launch.
Note: While idle, calling it again re-assembles the runtime with the new config (switching apiHost / model needs no cleanup() first, and the injected token is kept); it is a no-op with a warning only when a Travel is in flight, in which case end() it first. An invalid config leaves the current state unchanged — the runtime already in effect is not affected.
Signature
Return value
Bool — whether the config passed this time took effect. It is false in two cases: the config is invalid (apiHost / model blank or not forming a valid gateway URL), or a Travel in flight caused this call to be ignored; in both cases the runtime keeps its previous state.
isReady to judge success when switching config: if the re-initialize is rejected, the previous config is still in effect and isReady remains true. isReady answers "is the engine usable now"; this return value answers "did the config I just passed take effect".Parameters
Field | Type | Required | Description |
|---|---|---|---|
|
| Yes |
|
mode: with per-mode models, each model is its own gateway route, so a single initialize only serves worlds of one mode. If your app offers worlds in several modes, just call initialize() again with the matching model before entering a world of a different mode — while idle the latest config wins, no cleanup() is needed and the injected token is kept; while a Travel is in flight the call is ignored, in which case end() it first. A model that does not match the world's mode is rejected by the gateway with AccessDenied, normalized to 106003.OysterLog
Configure and take over the SDK's internal logging, printing it into your own logging module. Provides setMinimumLevel(_:) to set the level and setHandler(_:) for custom output (see the "Quick Start" example).
updateToken(_:)
Inject / update the HTTP auth token (Bailian temporary API Key; see the "Authentication Model" section).
When to use: After initialize, callable at any time; re-exchange it and call again after the token expires or after receiving an auth-related error (101001 / 101002).
Note: A no-op with a warning when not initialized.
Signature
Parameters
Field | Type | Required | Description |
|---|---|---|---|
|
| Yes | HTTP auth token (Bailian temporary API Key; see the "Authentication Model" section). |
createTravel(ticket:)
Create a session handle with a one-time ticket.
When to use: Call before each new experience; the returned handle is not yet connected and you must call travel.start() afterwards. The video is taken from the returned handle (see the "OysterTravel" section).
Note (synchronous throws): throws 100001 if not initialized; throws 103004 if called again before the previous Travel has been end()ed (each engine allows only one active Travel at a time).
Signature
Parameters
Field | Type | Required | Description |
|---|---|---|---|
|
| Yes | One-time credential; once created, it is considered occupied for this experience. |
Return value
Returns anOysterTravel session handle; not yet connected, you must call start() afterwards.
Errors
code | Description |
|---|---|
| Not |
| Called again before the previous Travel has |
cleanup()
Release the SDK's resources (end the active travel, the runtime configuration, the token).
When to use: When fully exiting the SDK or when you need to change the config.
Note: async — internally it deterministically end()s the current active travel first, then tears down the runtime, leaving no fire-and-forget. After release you can initialize again.
Signature
OysterTravel
The session handle created by createTravel; single-use, invalidated once a terminal state (end / server-side end / failure) is reached, requiring a fresh createTravel via the engine. It is also an ObservableObject (@Published status, can directly drive SwiftUI).
videoView / OysterVideoView(travel:)
The rendering entry for the remote picture — "the SDK provides the view, the host places it". For UIKit, take travel.videoView; for SwiftUI, use OysterVideoView(travel:).
When to use: Available as soon as the handle is created (repeated access returns the same view); mount it into any hierarchy, and once the engine is ready it renders automatically — mounting before or after start() both work, with no black screen.
Note: When the session ends, the SDK automatically releases the rendering binding; remove the view from the hierarchy as needed.
Signature
events / status / isEnded
events is the push stream of status changes + errors; status is the observable current external status; isEnded is a synchronously readable flag for whether a terminal state has been reached.
When to use: It is recommended to start consuming events before start(), to avoid missing early statuses.
Note: Each access to events returns an independent stream, supporting multi-subscription; unsubscribing = ending the for await iteration (or destroying the held Task). In SwiftUI you can directly observe status with @StateObject/@ObservedObject (errors still come through events). See the "Events and Status" section for details.
Signature
start() / start(maxExperienceTimeSec:)
Exchange the ticket captured at create time for the travel + RTC join configuration, and connect to play. On success the SDK automatically establishes the real-time connection and starts internal status polling, with the status surfaced through events.
Note (auto-end on no stream): The server delivers a "no-stream timeout" (default ~30s). If no stream is received within that duration after connecting (it never reaches running), the SDK automatically ends the experience, the status transitions to failed, and 105006 is surfaced via the .error of events (fatal; handle it by returning to the screen before "start experience", no need to time it yourself).
Signature
Parameters
Field | Type | Required | Description |
|---|---|---|---|
|
| No | (Optional) — requests the maximum duration (in seconds) of this world exploration (adventure) experience. The parameter is sent to the server as-is; the allowed values, the actually effective duration, and the auto-end timing on expiry are all decided by the server — the SDK performs no local validation; passing |
Return value
OysterStartTravelData (mode / version / encryptedTravelId, etc.; see the "Data Models" section), which determines the interaction UI.
mode of the ticket's world must match the model passed to initialize (guaranteed by the caller): with per-mode models, each model is its own gateway route, and start() sends the ticket to the route of the current model. The SDK does not and cannot verify this for you before the call — mode is delivered by the response of this very start() (i.e. OysterStartTravelData.mode); before the call the SDK holds only an opaque ticket and a model name, with no mode to compare against, and inferring the mode from the model name would be a guess at the server's naming, which the SDK does not do.Therefore: before entering a world of a different mode, call initialize() again with the matching model (while idle the latest config wins, no cleanup() needed, the token is kept; while a Travel is in flight the call is ignored, in which case end() it first). On a mismatch, this start() fails at the gateway; when diagnosing, first check "whether the current model and the mode of the world the current ticket belongs to are a matched set", then consult the credential error codes in the table below.Errors
code | Description |
|---|---|
| Credential invalid (also covers: the credential is valid, but the |
| Credential already used |
| World not ready |
| Current specification not enabled (e.g. the character acting (acting) specification) |
| Concurrency full/insufficient available capacity |
| Resource/server failure |
| Concurrent start |
pause() / resume()
Pause / resume the experience (idempotent).
When to use: Supported by directing (real-time directing) and acting (character acting) worlds; not supported by adventure. You can use the mode returned by start() to decide in advance whether to show the pause button. pause requires the current state to be running; resume requires paused.
Signature
Return value
ReturnsOysterTravelStateData (fields are in the "Data Models" section).
Errors
code | Description |
|---|---|
| No active experience |
| State/version not allowed |
| Mode mismatch |
rewind(toSec:)
Rewind to the specified seconds. On success the SDK automatically rejoins with the original rtcConfig and returns to playback.
When to use: Can be initiated only in the paused state, and only directing (real-time directing) worlds support it — neither acting nor adventure supports rewind; hide the rewind entry in those two modes and do not call it.
Signature
Parameters
Field | Type | Required | Description |
|---|---|---|---|
|
| Yes | The target second to rewind to. |
Return value
ReturnsOysterRewindTravelData (fields are in the "Data Models" section).
Errors
code | Description |
|---|---|
| No active experience |
| State not allowed |
end()
End the experience (idempotent, can be called repeatedly). After a successful call or an abnormal exit, the SDK automatically disconnects the real-time connection, stops polling, and releases all session resources; the ticket is invalidated at the same time, and the handle enters a terminal state.
When to use / Note: Whether the user exits actively or the experience ends passively (timer expiry, receiving .ended/.failed, page destruction), make sure a single end() is reached, otherwise the remote resources may not be released in time. It is recommended to funnel all exit paths into the same idempotent cleanup method.
Signature
Return value
ReturnsOysterEndTravelData (fields are in the "Data Models" section).
sendInstruct(content:) (real-time directing mode)
Send a text instruction to drive the storyline.
When to use: Real-time directing mode; sent directly when running, cached when paused and resent with the first frame after resume reconnects back to running.
Signature
Parameters
Field | Type | Required | Description |
|---|---|---|---|
|
| Yes | The text instruction content to send. |
Return value
ReturnsOysterSendInstructData (fields are in the "Data Models" section).
Errors
code | Description |
|---|---|
| No active experience |
| State not allowed |
| Called in world exploration mode |
| Input content rejected (content moderation) |
| Travel does not exist |
sendCommand(_:) / flushCommands() (world exploration mode)
sendCommand: Send direction/view/action control commands (seeOysterAdventureCommandin the "Data Models" section; fire-and-forget, no return, does not throw). Effective only in world exploration mode, whenrunning. External input can be high-frequency every frame; the SDK throttles internally (latest-wins sampling, frame merging at the RTC line rate), so the host does not need to throttle itself. Note that the server's response to commands itself has latency, so the actual effective time is not fixed.flushCommands: Called at the moment of "key release / input release", immediately resending the last waiting command in the queue; a pure no-op when there is no pending command, generating no new command.
Signature
Errors
code | Description |
|---|---|
| No active experience |
| Called in real-time directing mode |
| Real-time channel not ready/send failed |
.error of events, not throws.)
pauseLocalAudioCapture() / resumeLocalAudioCapture()
Temporarily release / restore the SDK's occupation of the local microphone capture.
When to use: When something like speech recognition needs exclusive access to the microphone, pause first and resume afterwards.
Signature
Events and Status
Events are attached to OysterTravel.events and are the SDK's active push channel to you, used to surface situations not triggered by your own calls (e.g. problems with the internally maintained real-time connection or status polling).
- SwiftUI:
OysterTravelis anObservableObject; directly use@StateObject/@ObservedObjectto observestatusand drive the UI; errors still come fromevents. - Imperative / UIKit: In a
Task,for await event in travel.events { ... }, andswitchover.statusChanged/.error; cancel the heldTaskwhen done.
OysterTravelStatus (5 process states + 2 terminal states):
Status | Description | Typical handling |
|---|---|---|
| after create, before start | — |
| connecting / reconnecting (internal connecting / reconnecting) | show connecting / reconnecting hint |
| stream ready, interactive (internal playing) | show picture and controls |
| pause accepted, awaiting server confirmation | show "pausing…" |
| paused (confirmed) | show paused state (only |
| ended (active end or server-side end). Terminal | wrap up and close the page |
| failed. Terminal | show error and wrap up |
ended / failed, the session has terminated, and all session operations (pause/resume/sendCommand…) no longer take effect. Callbacks may be triggered on the main thread, so you can update the UI directly.Data Models
@available(iOS 15.0, *). The return values/parameters below are SDK outputs, constructed in place internally with native Swift types (Date / TimeInterval / OysterTravelStatus); they are not Codable and do not expose wire (snake_case) details — wire decoding happens inside the SDK.- The rawValues of control commands are lower camelCase (e.g.
front/mouseLeft/jump); the enum values above are authoritative. - The external values of
modeareadventure(world exploration) /directing(real-time directing) /acting(character acting); theOysterModeValuedefinition is authoritative. aspectRatiois an open string (currently9:16/16:9, more may be added later). To decide orientation, parse it as awidth:heightratio instead of matching known values.
Error Codes
The SDK reports errors uniformly as OysterSDKError, and the type is always distinguished by code — do not judge the type by "which path the error came from": the same code may be thrown by a business method (async throws) or surfaced via the .error of events. For typed matching, use error.kind (see OysterErrorKind in the "Data Models" section).
Error codes: server 4xxxxx/5xxxxx, client-local 1xxxxx.
Server Error Codes (common)
code | Meaning | Suggested handling |
|---|---|---|
| Invalid parameters (invalid enum value, etc.) | Check the request parameters or the SDK version |
| Experience credential ( | Have the server re-issue the credential |
| Experience credential ( | Single-use credential; re-issue |
| World does not exist, has been deleted, or does not belong to the current developer (including the world in the credential having been deleted) | Pick a valid World again |
| World state not ready | Wait for the world to be ready before starting |
| The current API only allows the primary API Key | A temporary Key cannot be used for this API |
| Input content rejected (content moderation); applies to | Change the input content and retry |
| The current specification is not enabled | Do not retry as if capacity were full; switch to an enabled specification or contact support to enable it (typical: the account has not enabled the character acting (acting) specification) |
| Capacity configuration temporarily unavailable | Retry later |
| Resource does not exist (world / Travel ownership or no artifact) | Verify the ID / status |
| The request conflicts with the current resource state | Check the experience state |
| Concurrency for the current specification is full | Retry after an existing session ends (do not confuse with |
| Insufficient available capacity | Retry later |
| Internal system error | Retry later / report it |
| Inference resource allocation/internal service failure | Retry later |
Client-Local Error Codes
code | Meaning | SDK auto-terminates session | Suggested handling |
|---|---|---|---|
| Called before the SDK was initialized; also covers an | No (thrown synchronously, rejecting this call) |
|
| HTTP auth token not injected | No | Retry after |
| HTTP auth token invalid / rejected | No | Re-exchange the token, then |
| No active experience currently | No (rejecting this call) |
|
| The current state/version does not allow this operation | No (rejecting this call) | Check the experience state / |
| Mode mismatch (e.g. | No (rejecting this call) | Pick the matching API by |
| Concurrent create/start of an experience | No (thrown synchronously) | Serialize the calls, |
| Real-time connection failed | Yes | End and restart |
| Real-time join timeout | Yes | End and restart |
| Timeout waiting for the first video frame | Yes | End and restart |
| Real-time channel not ready/send failed | Depends (active send failure; heartbeat is report-only) | Send after |
| Callback timeout (default 30s) | No | Retry, and increase |
| No stream after joining; the SDK auto-ends the experience | Yes | End and restart |
| Local network error | No | Retryable |
| Response parsing failed | Depends | Upgrade the SDK / report |
| No recognizable error code carried / proxy string error code | No | Retryable |
| Remotely disabled by the server feature switch (full shutdown or version too low; see | Yes | Prompt the user per |
OysterSDKError has no isFatal). Semantically, "fatal" specifically means whether the SDK actively terminates the session (disconnecting RTC and releasing the whole session) —
- Errors that auto-terminate the session (e.g.
105001/105002/105003/105006/108001): the host perceives them from the terminal state of the state machine (status → failed, surfaced via the.statusChangedofevents), and returns to the screen before "start experience" accordingly, with no need to judge fatality itself. - Call-rejection errors (
100001/103001/103002/103003/103004): thrown synchronously / the call is rejected when you actively call; they do not terminate the session. - Other non-fatal errors (e.g.
101001/101002/105005/106001/106003): they do not terminate the session; retry as suggested or continue after re-injecting the token.
106001 may have two causes: a local network error, or an incorrect apiHost configuration. If retrying does not recover, check whether apiHost is configured correctly.106003 appearing after you fill in model: first check whether the model name and version are correct and enabled for the current account, and confirm that apiHost, the token, and the model belong to the same account and region — on a mismatch the gateway rejects with AccessDenied and normalizes it to this code.