tencent cloud

Mobile Live Video Broadcasting

Quick Start (iOS)

다운로드
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-11-18 11:33:45
This guide walks you through integrating the core component AtomicLiveView from the AtomicXCore SDK, along with AtomicPusher (for host streaming) and AtomicPlayer (for audience playback), to quickly build a basic live streaming app supporting host broadcasting and audience viewing.

Key Features

AtomicLiveView is a lightweight UIView designed specifically for live streaming. It acts as the canvas for your video layout. On the host side, AtomicPusher manages local audio/video capture and streaming. On the audience side, AtomicPlayer handles stream playback. Both components use setView to render video onto the same AtomicLiveView. You only need to focus on building your UI and interaction logic.
The diagram below illustrates where AtomicLiveView fits within the live streaming interface:


Prerequisites

Step 1: Activate Service

See Activate the Service to obtain either a trial or paid version of the SDK.

Step 2: Import AtomicXCore into Your Project

1. Install the component: Add pod 'AtomicXCore' to your Podfile and run pod install.
target 'xxxx' do
pod 'AtomicXCore', '~> 5.3'
end
2. Configure app permissions: Add camera and microphone usage descriptions to your app's Info.plist.
<key>NSCameraUsageDescription</key>
<string>TUILiveKit requires access to your camera. Video recording will have visuals only after enabling.</string>
<key>NSMicrophoneUsageDescription</key>
<string>TUILiveKit requires access to your microphone. Video recording will have audio only after enabling.</string>




Step 3: Implement Login Logic

Call LoginStore.shared.login in your project to complete login. This step is required before using any features in AtomicXCore.
Important:
Call LoginStore.shared.login only after your app's own user account login is successful. This ensures your login logic remains clear and consistent.
import AtomicXCore

// AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
LoginStore.shared.login(sdkAppID: 1400000001, // Replace with your SDKAppID
userID: "test_001", // Replace with your UserID
userSig: "xxxxxxxxxxx") { result in // Replace with your UserSig
switch result {
case .success(let info):
debugPrint("login success")
case .failure(let error):
debugPrint("login failed code:\\(error.code), message:\\(error.message)")
}
}
return true
}
Login API Parameter Description:
Parameter
Type
Description
sdkAppId
int
The ID of the live application created in the Console.
userId
string
Unique identifier for the current user. Use only letters, numbers, hyphens, and underscores. Avoid simple IDs like 1, 123, etc., to prevent multi-device login conflicts.
userSig
string
A ticket for Tencent Cloud authentication. Please note:
Development Environment: You can use the local GenerateTestUserSig.genTestSig function to generate a UserSig or generate a temporary UserSig via the UserSig Generation Tool.
Production Environment: To prevent key leakage, you must use a server-side method to generate UserSig. For details, see Generating UserSig on the Server.

Build Basic Live Room

Step 1: Implement Host Streaming

Follow these steps to quickly set up host video streaming:



1. Initialize Host Streaming View
In your host view controller, create an AtomicLiveView instance and set viewType to AtomicLiveViewType.pushView.
import AtomicXCore

// YourAnchorViewController is your host streaming view controller
class YourAnchorViewController: UIViewController {

private let liveId: String
// 1. Add AtomicLiveView as a property
private let liveView = AtomicLiveView(viewType:.pushView, frame: UIScreen.main.bounds)

// 2. Convenience initializer for liveId
public init(liveId: String) {
self.liveId = liveId
super.init(nibName: nil, bundle: nil)
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

public override func viewDidLoad() {
super.viewDidLoad()
// 3. Add the streaming view to the controller's view
view.addSubview(liveView)
}
}
2. Enable Camera and Microphone
Use DeviceStore's openLocalCamera and openLocalMicrophone APIs to enable the camera and microphone. AtomicLiveView automatically previews the camera stream. Example:
import AtomicXCore

class YourAnchorViewController: UIViewController {
// ... other code ...
public override func viewDidLoad() {
super.viewDidLoad()
// Enable devices
openDevices()
}

private func openDevices() {
// 1. Enable front camera
DeviceStore.shared.openLocalCamera(isFront: true, completion: nil)
// 2. Enable microphone
DeviceStore.shared.openLocalMicrophone(completion: nil)
}
}
3. Start Live Streaming
Bind the rendering view with AtomicPusher's setView, then call startPush to begin streaming.
import AtomicXCore

class YourAnchorViewController: UIViewController {

// ... other code ...

// Start streaming
private func startLive() {
// 1. Bind rendering view to AtomicPusher for local preview
AtomicPusher.shared.setView(liveView)

// 2. Configure live room info
var config = PusherInfo()
config.liveID = self.liveId // Set live room ID
config.liveName = "test live" // Set live room name

// 3. Start streaming
AtomicPusher.shared.startPush(config: config)
debugPrint("startPush")
}
}
PusherInfo Parameter Details
Parameter Name
Type|
Attribute
Description
liveID
String
Required
Unique identifier for the live room.
liveName
String
Optional
Title of the live room.
notice
String
Optional
Announcement for the live room.
metaData
[String: String]
Optional
Custom metadata for the live room.
isPublicVisible
Bool
Optional
Whether the room is publicly visible (true: yes, false: no).
coverURL
String
Optional
Cover image URL for the live room.
backgroundURL
String
Optional
Cover image URL for the live room.
categoryList
[NSNumber]
Optional
Background image URL for the live room.
4. End Live Streaming
When the host ends the stream, call AtomicPusher's stopPush to stop streaming. The SDK will handle stopping the stream and destroying the room.
import AtomicXCore

class YourAnchorViewController: UIViewController {

// ... other code ...

// End streaming
private func stopLive() {
AtomicPusher.shared.stopPush()
debugPrint("stopPush")
}
}

Step 2: Implement Audience Viewing

Follow these steps to enable audience live viewing:



1. Initialize Audience Playback Page
In your audience view controller, create an AtomicLiveView instance and set viewType to AtomicLiveViewType.playView.
import AtomicXCore

// YourAudienceViewController is your audience viewing controller
class YourAudienceViewController: UIViewController {

// 1. Initialize playback page
private let liveView = AtomicLiveView(viewType:.playView, frame: UIScreen.main.bounds)
private let player = AtomicPlayer()
private let liveId: String

public init(liveId: String) {
self.liveId = liveId
super.init(nibName: nil, bundle: nil)
// 2. Bind rendering view
player.setView(liveView)
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

public override func viewDidLoad() {
super.viewDidLoad()
// 3. Add playback page to your view
view.addSubview(liveView)
}
}
2. Enter Live Room
Bind the rendering view with AtomicPlayer's setView, then call joinChannel to enter the live room. After joining, call startPlay to play the stream.
import AtomicXCore

class YourAudienceViewController: UIViewController {
// ... other code ...

public override func viewDidLoad() {
super.viewDidLoad()
// 3. Add playback page
view.addSubview(liveView)

// 4. Enter live room
joinLive()
}

private func joinLive() {
// Enter live room; after success, start playback
// - liveId: Same as host's liveId
player.joinChannel(liveID: liveId) { [weak self] result in
guard let self = self else { return }
switch result {
case .success:
// Playback URL is generated as livekit://liveid=<liveId>
player.startPlay(url: "livekit://liveid=\\(liveId)")
debugPrint("joinChannel success")
case .failure(let error):
debugPrint("joinChannel error \\(error.message)")
// If joining fails, exit the page
// self.dismiss(animated: true)
default: break
}
}
}
}
3. Exit Live Stream
When the audience leaves the live room, call AtomicPlayer's stopPlay and leaveChannel to exit. The SDK will stop playback and exit the room.
import AtomicXCore

class YourAudienceViewController: UIViewController {

// ... other code ...

// Exit live stream
private func leaveLive() {
player.stopPlay()
player.leaveChannel()
debugPrint("leaveLive success")
}
}

Step 3: Listen for Live Events

After the audience enters the live room, handle passive events such as the host ending the stream or the audience being kicked out. If you don't listen for these events, the audience UI may remain on a black screen, affecting user experience.
Subscribe to AtomicPlayer's playerEvent to listen for events.
import AtomicXCore
import Combine // 1. Import Combine framework

class YourAudienceViewController: UIViewController {

// ... other code (liveView, player, liveId, init, deinit, joinLive, leaveLive, etc.) ...

// 2. Define cancellableSet to manage subscriptions
private var cancellableSet: Set<AnyCancellable> = []

public override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(liveView)
// 3. Listen for live events
setupLiveEventListener()
// 4. Enter live room
joinLive()
}

// 5. Set up event listening
private func setupLiveEventListener() {
player.playerEvent
.receive(on: RunLoop.main) // Ensure UI updates are on the main thread
.sink { [weak self] event in
guard let self = self else { return }
switch event {
case .liveEnded(let reason):
// Live ended
debugPrint("Live ended. reason: \\(reason.rawValue)")
// Handle exit logic, e.g., close the page
// self.dismiss(animated: true)
case .kickedOut(let reason, let message):
// Audience kicked out
debugPrint("Kicked out of live. reason: \\(reason.rawValue), message: \\(message)")
// Handle exit logic
// self.dismiss(animated: true)
}
}
.store(in: &cancellableSet) // Manage subscription
}

// ... joinLive() and leaveLive() methods ...
}

Run Effect

After integrating AtomicLiveView, you'll have a clean video rendering view. The host streams via AtomicPusher, the audience plays via AtomicPlayer, and both render to this view. Note: AtomicLiveView does not include interactive UI. See Enrich Live Streaming Scenarios to enhance your live streaming experience.
Layout Type
Dynamic Grid Layout
Floating Window Layout
Fixed Grid Layout
Fixed Window Layout
Template ID
600
601
800
801
Description
Default layout, dynamically adjusts grid size based on the number of co-hosts.
Co-host guests are displayed as floating windows.
Fixed number of co-hosts, each guest occupies a fixed grid.
Fixed number of co-hosts, guests are displayed as fixed windows.
Run Effect













Enrich Live Streaming Scenarios

After implementing basic live streaming, use the following guides to add interactive features to your live stream.
Live Feature
Feature Introduction
Feature Stores
Implementation Guide
Audience Audio/Video Co-hosting
Audience can request to take a mic seat and interact with the host in real-time video.
Host Cross-room Co-hosting PK
Hosts from different rooms can connect for interaction or PK.
Add Live Comments Chat
Audience can send and receive real-time text messages in the live room.
Build Gift System
Audience can send virtual gifts to the host, increasing interaction and fun.
GiftStore

API Documentation

Store/Component
Feature Description
API Documentation
AtomicPusher
Host streaming: Local audio/video capture and preview, start/stop streaming, live room info update, streaming status/statistics, event callbacks.
AtomicPlayer
Audience playback: Render view binding, join/leave channel, start/stop playback, playback status/statistics, event callbacks.
LiveListStore
Live room lifecycle management: Create/join/leave/destroy room, query room list, modify live info (name, announcement, etc.), listen for live status (e.g., kicked out, ended).
DeviceStore
Audio/video device control: Microphone (switch/volume), camera (switch/swap/quality), screen sharing, real-time device status monitoring.
CoGuestStore
Audience co-hosting management: Co-host request/invite/accept/reject, co-host member permission control (microphone/camera), status sync.
CoHostStore
Host cross-room co-hosting: Supports multiple layout templates (dynamic grid, etc.), initiate/accept/reject co-hosting, co-host interaction management.
BattleStore
Host PK battle: Initiate PK (set duration/opponent), manage PK status (start/end), sync scores, listen for battle results.
GiftStore
Gift interaction: Get gift list, send/receive gifts, listen for gift events (including sender, gift details).
BarrageStore
Live comments: Send text/custom comments, maintain comment list, real-time comment status monitoring.
LikeStore
Like interaction: Send likes, listen for like events, sync total like count.
LiveAudienceStore
Audience management: Get real-time audience list (ID/name/avatar), count audience, listen for audience entry/exit events.
AudioEffectStore
Audio effects: Voice changer (child/male voice), reverb (KTV, etc.), monitor adjustment, real-time effect switching.
BaseBeautyStore
Basic beauty: Adjust smoothing/whitening/rosiness (0-100 levels), reset beauty state, sync effect parameters.

FAQs

Why is the screen black with no video after the host calls startPush or the audience calls joinChannel?

Check setView: Make sure you have called setView to bind AtomicLiveView to AtomicPusher or AtomicPlayer before starting streaming or playback.
Check device permissions: Ensure the app has camera and microphone permissions.
Check host side: Confirm the host has called DeviceStore.shared.openLocalCamera(isFront: true) to enable the camera.
Check network: Verify the device has a stable network connection.

Why does the host see a local video preview after starting streaming, but the preview is black before starting?

Check host side: Ensure the host streaming view AtomicLiveView uses viewType as AtomicLiveViewType.pushView.
Check audience side: Ensure the audience playback view AtomicLiveView uses viewType as AtomicLiveViewType.playView.

rsync fails to copy third-party library resources due to insufficient permissions

For example, when integrating the SnapKit framework with Xcode, you may encounter the following build error:
rsync(xxxx):1:1: SnapKit.framework/SnapKit_Privacy.bundle/: mkpathat: Operation not permitted

Cause

Xcode's user script sandbox mechanism restricts the rsync script's write permissions to SnapKit.framework resource files during the build process, causing the SnapKit_Privacy.bundle in the framework to fail to copy properly.

Solution Steps

1. After disabling user script sandboxing, open your Xcode project, go to Build Settings, search for User Script Sandboxing (or ENABLE_USER_SCRIPT_SANDBOXING), and change its value from YES to NO.
2. Clean and rebuild the project by executing Product → Clean Build Folder to clear the project cache, then recompile and run.


도움말 및 지원

문제 해결에 도움이 되었나요?

피드백