Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?



This guide provides you with an overview of the key objects you'll use in the Programmable Video API to build your video application with the Twilio Programmable Video iOS SDK.

Note: If you haven’t already done so, then take a look at the Twilio Video iOS QuickStart Application [Swift, Objective-C]. Once you've played with the QuickStart, come back to this guide for more detail on how to add video to your own app.

WebRTCをお使いいただいた経験があるなら、Programmable Videoは完成度の高いオーディオおよびビデオアプリケーションの構築を容易にするために、WebRTCの下位レベルAPIの単純なラッパーを提供していることに気づかれるでしょう。 依然としてより下位レベルのプリミティブにアクセスできますが、入門には必要ありません。

加えて、Programmable VideoはWebRTCを使用して洗練されたアプリケーションを構築するために必要な不足したピース: グローバルSTUN/TURNリレー、大規模な電話会議および録音用のメディアサービス、そしてシグナリングのためのインフラが全て含まれています。

Video API概要

まずは、Programmable Video APIの概要からはじめましょう:

  • Roomはリアルタイムのオーディオ、ビデオ、そして画面共有セッションを表し、これはProgrammable Videoアプリケーションにおける基本となる構成要素になります。
  • In a Peer-to-peer Room, media flows directly between participants. Supports up to 10 participants in a mesh topology.
  • In a Group Room, media is routed through Twilio's Media Servers. Supports up to 50 participants.
  • Participants は、Roomに接続され、他のクライアントとオーディオまたは(および)ビデオのメディアと共有しているクライアントアプリケーションを表します。
  • Tracks は、Roomと共有されているオーディオとビデオのストリームを表します。
  • LocalTracks represent the audio and video captured from the local microphone and camera.
  • RemoteTracks represent the audio and video tracks from other participants connected to the Room.



To start using the iOS Programmable Video SDK in your apps, you need to perform a few basic tasks first.

1. Get the Programmable Video iOS SDK

The Twilio Video iOS SDK dynamic framework can be installed using Carthage, CocoaPods or manually, as you prefer. As of the 2.5.2 release, the Twilio Video iOS SDK is also distributed as a static library which can be manually installed.


You can add Programmable Video for iOS by adding the following line to your Cartfile:

github "twilio/twilio-video-ios"

続いて、carthage bootstrap を実行します。 (SDKを更新している場合は carthage update)

On your application targets’ General settings page, in the Linked Frameworks and Libraries section, drag and drop each framework you want to use from the Carthage/Build folder on disk.

On your application targets’ Build Phases settings tab, click the “+” icon and choose New Run Script Phase. Create a Run Script in which you specify your shell (ex: /bin/sh), add the following contents to the script area below the shell:

/usr/local/bin/carthage copy-frameworks

Add the paths to the frameworks you want to use under Input Files, e.g.:

source 'https://github.com/CocoaPods/Specs'

platform :ios, '9.0'

target 'TARGET_NAME' do
    pod 'TwilioVideo', '~> 2.9'

そして、pod install を実行してプロジェクトに依存関係をインストールします。


TwilioVideo.framework は既存のプロジェクトにドラッグ&ドロップできる動的なiOSフレームワークとして配布されています。

View all Video iOS Releases here or just download the latest Video dynamic framework here.

フレームワークをダウンロード、展開したら、XcodeプロジェクトのGeneral 設定ページに移動します。 Embedded Binariesセクションに、TwilioVideo.framework をドラッグ&ドロップします。 "Copy items if needed"にチェックが入っているかどうか確認し、Finishをクリックします。 これで、LibrariesセクションのEmbedded BinariesおよびLinked Frameworks双方に TwilioVideo.framework が追加されました。

Next, you will need to open your project's Linked Frameworks and Libraries configuration. You should see TwilioVideo.framework there already. Add the following frameworks to that list:

  • AudioToolbox.framework
  • VideoToolbox.framework
  • AVFoundation.framework
  • CoreTelephony.framework
  • GLKit.framework
  • CoreMedia.framework
  • SystemConfiguration.framework
  • libc++.tbd

In your Build Settings, you will also need to modify Other Linker Flags to include -ObjC.

Before distributing your app to the  App Store, you will need to strip the simulator binaries from the embedded framework. Navigate to your target's Build Phases screen and create a new Run Script Phase. Ensure that this new run script phase is after the Embed Frameworks phase. Paste the following command in the script text field:

/bin/bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/TwilioVideo.framework/remove_archs"
Manual static library integration

libTwilioVideo is distributed as a static iOS library that you can drag and drop into you existing projects.

View all Video iOS Releases here or just download the latest Video static library here.

Once you've downloaded and unpacked the static library, drag and drop the lib and headers folders into your project. Ensure that "Copy items if needed" is checked and press Finish. This will add libTwilioVideo.a to the Linked Frameworks and Libraries section.

Next, you will need to open your project's Linked Frameworks and Libraries configuration. You should see libTwilioVideo.a there already. Add the following frameworks to that list:

  • AudioToolbox.framework
  • VideoToolbox.framework
  • AVFoundation.framework
  • CoreTelephony.framework
  • GLKit.framework
  • CoreMedia.framework
  • SystemConfiguration.framework
  • libc++.tbd

In your Build Settings, you will also need to modify Other Linker Flags to include -ObjC.

Background Modes

To allow a connection to a Room to be persisted while an application is running in the background, you must select the Audio, AirPlay, and Picture in Picture background mode from the Capabilities project settings page.


The iOS SDK supports iOS 9.0 or higher. It is built for armv7, arm64, x86 and x86_64 architectures with Bitcode slices for armv7 and arm64 devices. Devices based on the A5 SoC (iPhone 4s, iPad 2, iPad Mini 1, iPod Touch 5G) are not supported, and the SDK will not perform well on them.

Supported Xcode versions and Bitcode

The TwilioVideo.framework is built with Xcode 9.4. The framework can successfully be consumed with previous versions of Xcode. However, re-compiling Bitcode when exporting for Ad Hoc or Enterprise distribution requires the use of Xcode 9.x.

2. Get an API Key


For the purposes of this guide, we will create our API Key from the Twilio Console.

  • Go to the API Keys section under Tools in the Twilio Console.
  • Click on “Create a New API Key”, add a friendly name and save your Key and Secret.

3. Generate an Access Token

To execute the code samples below, you can use the Testing Tools page in the Twilio Console to generate an Access Token. An Access Token is a short-lived credential used to authenticate your client-side application to Twilio.

In a production application, your back-end server will need to generate an Access Token for every user in your application. An Access Token is a short-lived credential used to authenticate your client-side application to Twilio. Visit the User Identity and Access Token guide to learn more.


Call TwilioVideo.connect() to connect to a Room from your iOS application. Once connected, you can send and receive audio and video streams with other Participants who are connected to the Room.

@IBAction func createARoom(sender: AnyObject) {
    let connectOptions = TVIConnectOptions.init(token: accessToken) { (builder) in
        builder.roomName = "my-room"
    room = TwilioVideo.connect(with: connectOptions, delegate: self)

// MARK: TVIRoomDelegate

func didConnectToRoom(room: TVIRoom) {
    print("Did connect to Room")

Roomへの接続時には、アクセストークンを渡すことが必要です。 またオプションで、下記を渡すこともできます:

  • Local audio, video or data tracks, to begin sharing pre-created local media with other Participants in the Room upon connecting.
  • ルーム名: 参加したいルームの名前を動的に指定できます。 (メモ: ルーム名をアクセストークンにエンコードできます。 こうすることでユーザーはトークンで指定されたRoomにのみ接続できます。)
  • ICEトランスポートポリシー: テスト用途として、強制的にTURNリレー経由で通話を行えるようになります。

Roomの名前には、参加したいRoomを指定します。 その名前のRoomがまだ存在していない場合、接続に先立って作成されます。 ルームがすでにアクティブな場合はルームに接続され、同じルームに接続されている他の参加者からの通知を受信します。 ルーム名はアカウント内で一意でなければなりません。

また、Rooms REST APIを使用してRoomに接続することも可能です。 さらなる詳細については、REST API Roomsリソースを参照してください。

Example: Create a Room called DailyStandup

 curl -XPOST 'https://video.twilio.com/v1/Rooms' \
 -u '{API Key SID}:{API Secret}' \
 -d 'UniqueName=DailyStandup'

注 : Type属性を指定しない場合、Twilioは既定でGroupルームを作成します。


You can also set the room type from the Room Settings page in the Twilio Video Console. Twilio will use the room type set on Room Settings page, when you create a room from the client-side or the REST API.

メモ: Twilioは、Room設定ページの既定としてRoomタイプをGroupに設定します。

StatusCallback URLが設定されている場合、Roomが作成されると、Twilioはroom-created Webhookイベントを呼び出します。 クライアント側からRoomを作成したい場合、Room設定ページからStatusCallback URLを設定できます。 REST APIでRoomを作成する場合、Room作成時にStatusCallback URLを指定することが必要です。

 curl -XPOST 'https://video.twilio.com/v1/Rooms' \
 -u '{API Key SID}:{API Secret}' \
 -d 'UniqueName=DailyStandup' \
 -d 'StatusCallback=https://hooks.yoursite.com/room-events' \
 -d 'StatusCallbackMethod=POST' \
 -d 'Type=group'

Enabling Room Recordings

Recordings can be enabled only on Group Rooms. Set Recordings to Enabled to record participants when they connect to a Group Room. Recordings can also be enabled on Group Rooms through via the Rest API at Room creation time by setting the RecordParticipantsOnConnect property to true.

curl -XPOST 'https://video.twilio.com/v1/Rooms' \
-d 'UniqueName=DailyStandup' \
-d 'Type=group' \
-d 'RecordParticipantsOnConnect=true' \
-d 'StatusCallback=http://example.org'


If you'd like to join a Room you know already exists, you handle that exactly the same way as creating a room: just pass the Room name to the connect method. Once in a Room, you'll receive a room:participantDidConnect: callback for each Participant that successfully joins. Querying the remoteParticipants getter will return any existing Participants who have already joined the Room.

@IBAction func joinRoom(sender: AnyObject) {
    let connectOptions = TVIConnectOptions.init(block: { (builder) in
        builder.roomName = "existing-room"
    room = TwilioVideo.connect(with: connectOptions, delegate: self)

// MARK: TVIRoomDelegate

func didConnectToRoom(room: TVIRoom) {
    print("Did connect to room")



iOSアプリケーションでは、TVILocalAudioTrackを作成することでオーディオの取り込みを開始し、TVIVideoCapturerと関連づけられたTVILocalVideoTrackを作成することでビデオの取り込みを開始します。 iOS Video SDKはカメラおよび画面共有の双方に対して、カスタマイズ可能なビデオ取り込みを提供します。

// Create an audio track
var localAudioTrack = TVILocalAudioTrack()

// Create a data track
var localDataTrack = TVILocalDataTrack()

// Create a Capturer to provide content for the video track
var localVideoTrack : TVILocalVideoTrack?

// Create a video track with the capturer.
if let camera = TVICameraCapturer(source: .frontCamera) {
    localVideoTrack = TVILocalVideoTrack.init(capturer: camera)

Specify tracks at connect time

When the client joins a Room, the client can specify which Tracks they wish to share with other Participants. Imagine we want to share the audio and video Tracks we created earlier.

let connectOptions = TVIConnectOptions.init(token: accessToken) { (builder) in
    builder.roomName = "my-room"

    if let audioTrack = localAudioTrack {
        builder.audioTracks = [ audioTrack ]
    if let dataTrack = localDataTrack {
        builder.dataTracks = [ dataTrack ]
    if let videoTrack = localVideoTrack {
        builder.videoTracks = [ videoTrack ]

var room = TwilioVideo.connect(with: connectOptions, delegate: self)



When you join a Room, Participants may already be present. You can check for existing Participants in the roomDidConnect: callback by using the remoteParticipants getter.

room = TwilioVideo.connect(with: connectOptions, delegate: self)

// MARK: TVIRoomDelegate

func didConnect(to room: TVIRoom) {
    // The Local Participant
    if let localParticipant = room.localParticipant {
        print("Local identity \(localParticipant.identity)")

    // Connected participants
    let participants = room.remoteParticipants;
    print("Number of connected Participants \(participants.count)")

func room(_ room: TVIRoom, participantDidConnect participant: TVIRemoteParticipant) {
    print ("Participant \(participant.identity) has joined Room \(room.name)")

func room(_ room: TVIRoom, participantDidDisconnect participant: TVIRemoteParticipant) {
    print ("Participant \(participant.identity) has left Room \(room.name)")


When Participants connect to or disconnect from a Room that you're connected to, you'll be notified via an event listener: Similar to Room Events, Twilio will fire Participant events if the StatusCallback webhook URL is set when the Room is created. These events help your application keep track of the participants who join or leave a Room.

// MARK: TVIRoomDelegate

// First, we set a Participant Delegate when a Participant first connects:
func room(_ room: TVIRoom, participantDidConnect participant: TVIRemoteParticipant) {
    print("Participant connected: \(participant.identity!)")
    participant.delegate = self



// MARK: TVIRemoteParticipantDelegate

 * In the Participant Delegate, we can respond when the Participant adds a Video
 * Track by rendering it on screen.
func subscribed(to videoTrack: TVIRemoteVideoTrack,
                  publication: TVIRemoteVideoTrackPublication,
              for participant: TVIRemoteParticipant) {

    print("Participant \(participant.identity) added a video track.")

    self.remoteView = TVIVideoView.init(frame: self.view.bounds,


// MARK: TVIVideoViewDelegate

// Lastly, we can subscribe to important events on the VideoView
func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) {
    print("The dimensions of the video track changed to: \(dimensions.width)x\(dimensions.height)")



Sometimes you need to make sure you're looking fantastic before entering a Room. We get it. The iOS SDK provides a means to render a local camera preview outside the context of an active Room:

// Use TVICameraCapturer to produce video from the device's front camera.

if let camera = TVICameraCapturer(source: .frontCamera),
    let videoTrack = TVILocalVideoTrack(capturer: camera) {

    // TVIVideoView is a TVIVideoRenderer and can be added to any TVIVideoTrack.
    let renderer = TVIVideoView(frame: view.bounds)

    // Add renderer to the video track

    self.localVideoTrack = videoTrack
    self.camera = camera
} else {
    print("Couldn't create TVICameraCapturer or TVILocalVideoTrack")


現在参加しているルームから切断できます。 他の参加者は participantDisconnected イベントを受信します。

// To disconnect from a Room, we call:

// This results in a callback to TVIRoomDelegate#room:didDisconnectWithError

// MARK: TVIRoomDelegate

func room(_ room: TVIRoom, didDisconnectWithError error: Error?) {
    print("Disconnected from room \(room.name)")

Room reconnection

As of the 2.7.0 release, the Video SDK will raise notifications when a Room is reconnecting due to a network disruption. A Room reconnection is triggered due to a signaling or media reconnection event. To capture when a reconnection is triggered or that it has reconnected:

// MARK: TVIRoomDelegate

// Error will be either TVIErrorSignalingConnectionDisconnectedError or TVIErrorMediaConnectionError
func room(_ room: TVIRoom, isReconnectingWithError error: Error) {
    print("Reconnecting to room \(room.name), error = \(String(describing: error))")

func didReconnect(to room: TVIRoom) {
    print("Reconnected to room \(room.name)")

Reconnections in a Peer-to-Peer Room

In a Peer-to-Peer Room, each Participant has media connections to all the other Participants in the Room. If all media connections between the LocalParticipant and all other Participants are broken, then the LocalParticipant's Room will enter the reconnecting state until media connectivity with at least one Participant is re-established.

Reconnections and the UIApplication lifecycle

There are certain instances when an application is put into the background that both the signaling and media connection are closed, which will cause the reconnecting delegate method to be invoked:

  • When connected to a Peer-to-Peer Room with no Remote Participants.
  • When connected to a Peer-to-Peer Room with other Remote Participants and no shared audio tracks.
  • When connected to a Group Room with no shared audio tracks.

Server-side control

The Programmable Video REST API allows you to control your video applications from your back-end server via HTTP requests. To learn more check out the Programmable Video REST API docs.

Rate this page:


We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.