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. Once you've played with the QuickStart, come back to this guide for more detail on how to add video to your own app.
If you've worked with WebRTC in the past, you'll find that Programmable Video provides a simple wrapper around WebRTC's lower-level APIs to make it easy to build rich audio and video applications. You can still access lower-level primitives, but that's not required to get started.
Additionally, Programmable Video provides the missing pieces required to use WebRTC to build sophisticated applications: Global STUN/TURN relays, media services for large-scale group conferences and recording, and signaling infrastructure are all included.
Let's start with an overview of the Programmable Video API:
Room
represents a real-time audio, video, and/or screen-share session, and is the basic building block for a Programmable Video application.Peer-to-peer Room
, media flows directly between participants. Supports up to 10 participants in a mesh topology.Group Room
, media is routed through Twilio's Media Servers.
Supports up to 50 participants.Participants
represent client applications that are connected to a Room and sharing audio and/or video media with one another.Tracks
represent the individual audio and video media streams that are shared within a 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.The following code samples illustrate common tasks that you as a developer may wish to perform related to a Room and its Participants.
To start using the iOS Programmable Video SDK in your apps, you need to perform a few basic tasks first.
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" ~> 2.12
Then run carthage bootstrap
(or carthage update
if you are updating your SDKs)
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.:
$(SRCROOT)/Carthage/Build/iOS/TwilioVideo.framework
1source 'https://github.com/CocoaPods/Specs'23platform :ios, '9.0'45target 'TARGET_NAME' do6pod 'TwilioVideo', '~> 2.12'7end
Then run pod install
to install the dependencies to your project.
TwilioVideo.framework
is distributed as a dynamic iOS framework that you can drag and drop into your existing projects.
View all Video iOS Releases here or just download the latest Video dynamic framework here.
Once you've downloaded and unpacked the framework, navigate to your Xcode project's General settings page. Drag and drop TwilioVideo.framework
onto the Embedded Binaries section. Ensure that "Copy items if needed" is checked and press Finish. This will add TwilioVideo.framework
to both the Embedded Binaries and Linked Frameworks and Libraries sections.
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"
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
.
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.
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.
API Keys represent credentials to access the Twilio API. They are used for two purposes:
For the purposes of this guide, we will create our API Key from the Twilio Console.
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.
1@IBAction func createARoom(sender: AnyObject) {2let connectOptions = TVIConnectOptions(token: accessToken) { (builder) in3builder.roomName = "my-room"4}5room = TwilioVideo.connect(with: connectOptions, delegate: self)6}78// MARK: TVIRoomDelegate910func didConnectToRoom(room: TVIRoom) {11print("Did connect to Room")12}
You must pass the Access Token when connecting to a Room. You may also optionally pass the following:
The name of the Room specifies which Room you wish to join. If a Room by that name does not already exist, it will be created upon connection. If a Room by that name is already active, you'll be connected to the Room and receive notifications from any other Participants also connected to the same Room. Room names must be unique within an account.
You can also create a Room using the Rooms REST API. Look at the REST API Rooms resource docs for more details.
Example: Create a Room called DailyStandup
1curl -XPOST 'https://video.twilio.com/v1/Rooms' \2-u '{API Key SID}:{API Secret}' \3-d 'UniqueName=DailyStandup'
Note: If you don't specify a Type attribute, then Twilio will create a Group Room by default.
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.
Note: Twilio will set the Room Type as Group by default on the Room Settings page.
Once a Room is created, Twilio will fire a room-created
webhook event, if the StatusCallback URL is set. You can set the StatusCallback URL on the Room Settings page, if you want create a room from the client-side.
If you create a room using the REST API, then you need to provide a StatusCallback URL while creating the room.
1curl -XPOST 'https://video.twilio.com/v1/Rooms' \2-u '{API Key SID}:{API Secret}' \3-d 'UniqueName=DailyStandup' \4-d 'StatusCallback=https://hooks.yoursite.com/room-events' \5-d 'StatusCallbackMethod=POST' \6-d 'Type=group'
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
.
1curl -XPOST 'https://video.twilio.com/v1/Rooms' \2-u 'SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_api_key_secret' \3-d 'UniqueName=DailyStandup' \4-d 'Type=group' \5-d 'RecordParticipantsOnConnect=true' \6-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.
1@IBAction func joinRoom(sender: AnyObject) {2let connectOptions = TVIConnectOptions.init(block: { (builder) in3builder.roomName = "existing-room"4})5room = TwilioVideo.connect(with: connectOptions, delegate: self)6}78// MARK: TVIRoomDelegate910func didConnectToRoom(room: TVIRoom) {11print("Did connect to room")12}
You can capture local media from your device's microphone, camera or screen-share on different platforms in the following ways:
In an iOS application, begin capturing audio data by creating a TVILocalAudioTrack
, and begin capturing video by creating a TVILocalVideoTrack
with an associated TVIVideoCapturer
. The iOS Video SDK provides customizable video capturers for both camera and screen capture.
1// Create an audio track2var localAudioTrack = TVILocalAudioTrack()34// Create a data track5var localDataTrack = TVILocalDataTrack()67// Create a Capturer to provide content for the video track8var localVideoTrack : TVILocalVideoTrack?910// Create a video track with the capturer.11if let camera = TVICameraCapturer(source: .frontCamera) {12localVideoTrack = TVILocalVideoTrack.init(capturer: camera)13}
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.
1let connectOptions = TVIConnectOptions(token: accessToken) { (builder) in2builder.roomName = "my-room"34if let audioTrack = localAudioTrack {5builder.audioTracks = [ audioTrack ]6}7if let dataTrack = localDataTrack {8builder.dataTracks = [ dataTrack ]9}10if let videoTrack = localVideoTrack {11builder.videoTracks = [ videoTrack ]12}13}1415var room = TwilioVideo.connect(with: connectOptions, delegate: self)
For some use cases (such as a ReplayKit broadcast extension) you may wish to connect as a publish-only Participant that is not subscribed to any Tracks. If you are connecting to a Group Room, you may disable automatic subscription behavior via ConnectOptions.
1let connectOptions = TVIConnectOptions(token: accessToken) { (builder) in2builder.isAutomaticSubscriptionEnabled = false3builder.roomName = "my-room"45if let audioTrack = localAudioTrack {6builder.audioTracks = [ audioTrack ]7}8}910var 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.
1room = TwilioVideo.connect(with: connectOptions, delegate: self)23// MARK: TVIRoomDelegate45func didConnect(to room: TVIRoom) {6// The Local Participant7if let localParticipant = room.localParticipant {8print("Local identity \(localParticipant.identity)")9}1011// Connected participants12let participants = room.remoteParticipants;13print("Number of connected Participants \(participants.count)")14}1516func room(_ room: TVIRoom, participantDidConnect participant: TVIRemoteParticipant) {17print ("Participant \(participant.identity) has joined Room \(room.name)")18}1920func room(_ room: TVIRoom, participantDidDisconnect participant: TVIRemoteParticipant) {21print ("Participant \(participant.identity) has left Room \(room.name)")22}
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.
1// MARK: TVIRoomDelegate23// First, we set a Participant Delegate when a Participant first connects:4func room(_ room: TVIRoom, participantDidConnect participant: TVIRemoteParticipant) {5print("Participant connected: \(participant.identity!)")6participant.delegate = self7}
To see the Video Tracks being sent by remote Participants, we need to render them to the screen:
1// MARK: TVIRemoteParticipantDelegate23/*4* In the Participant Delegate, we can respond when the Participant adds a Video5* Track by rendering it on screen.6*/7func subscribed(to videoTrack: TVIRemoteVideoTrack,8publication: TVIRemoteVideoTrackPublication,9for participant: TVIRemoteParticipant) {1011print("Participant \(participant.identity) added a video track.")1213self.remoteView = TVIVideoView.init(frame: self.view.bounds,14delegate:self)1516videoTrack.addRenderer(self.remoteView)17self.view.addSubview(self.remoteView!)18}1920// MARK: TVIVideoViewDelegate2122// Lastly, we can subscribe to important events on the VideoView23func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) {24print("The dimensions of the video track changed to: \(dimensions.width)x\(dimensions.height)")25self.view.setNeedsLayout()26}
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:
1// Use TVICameraCapturer to produce video from the device's front camera.23if let camera = TVICameraCapturer(source: .frontCamera),4let videoTrack = TVILocalVideoTrack(capturer: camera) {56// TVIVideoView is a TVIVideoRenderer and can be added to any TVIVideoTrack.7let renderer = TVIVideoView(frame: view.bounds)89// Add renderer to the video track10videoTrack.addRenderer(renderer)1112self.localVideoTrack = videoTrack13self.camera = camera14self.view.addSubview(renderer)15} else {16print("Couldn't create TVICameraCapturer or TVILocalVideoTrack")17}
You can disconnect from a Room you're currently participating in. Other Participants will receive a participantDisconnected
event.
1// To disconnect from a Room, we call:2room?.disconnect()34// This results in a callback to TVIRoomDelegate#room\:didDisconnectWithError56// MARK: TVIRoomDelegate78func room(_ room: TVIRoom, didDisconnectWithError error: Error?) {9print("Disconnected from room \(room.name)")10}
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:
1// MARK: TVIRoomDelegate23// Error will be either TVIErrorSignalingConnectionDisconnectedError or TVIErrorMediaConnectionError4func room(_ room: TVIRoom, isReconnectingWithError error: Error) {5print("Reconnecting to room \(room.name), error = \(String(describing: error))")6}78func didReconnect(to room: TVIRoom) {9print("Reconnected to room \(room.name)")10}
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.
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:
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.