-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathViewController.swift
More file actions
457 lines (362 loc) · 18.5 KB
/
ViewController.swift
File metadata and controls
457 lines (362 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//
// ViewController.swift
// VideoQuickStart
//
// Copyright © 2016-2017 Twilio, Inc. All rights reserved.
//
import UIKit
import TwilioVideo
class ViewController: UIViewController {
// MARK: View Controller Members
// Configure access token manually for testing, if desired! Create one manually in the console
// at https://www.twilio.com/console/video/runtime/testing-tools
var accessToken = "TWILIO_ACCESS_TOKEN"
// Configure remote URL to fetch token from
var tokenUrl = "http://localhost:8000/token.php"
// Video SDK components
var room: TVIRoom?
var camera: TVICameraCapturer?
var localVideoTrack: TVILocalVideoTrack?
var localAudioTrack: TVILocalAudioTrack?
var remoteParticipant: TVIRemoteParticipant?
var remoteView: TVIVideoView?
// MARK: UI Element Outlets and handles
// `TVIVideoView` created from a storyboard
@IBOutlet weak var previewView: TVIVideoView!
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var roomTextField: UITextField!
@IBOutlet weak var roomLine: UIView!
@IBOutlet weak var roomLabel: UILabel!
@IBOutlet weak var micButton: UIButton!
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.title = "QuickStart"
self.messageLabel.adjustsFontSizeToFitWidth = true;
self.messageLabel.minimumScaleFactor = 0.75;
if PlatformUtils.isSimulator {
self.previewView.removeFromSuperview()
} else {
// Preview our local camera track in the local video preview view.
self.startPreview()
}
// Disconnect and mic button will be displayed when the Client is connected to a Room.
self.disconnectButton.isHidden = true
self.micButton.isHidden = true
self.roomTextField.autocapitalizationType = .none
self.roomTextField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
self.view.addGestureRecognizer(tap)
}
func setupRemoteVideoView() {
// Creating `TVIVideoView` programmatically
self.remoteView = TVIVideoView.init(frame: CGRect.zero, delegate:self)
self.view.insertSubview(self.remoteView!, at: 0)
// `TVIVideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit
// scaleAspectFit is the default mode when you create `TVIVideoView` programmatically.
self.remoteView!.contentMode = .scaleAspectFit;
let centerX = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerX)
let centerY = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerY)
let width = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.width,
multiplier: 1,
constant: 0);
self.view.addConstraint(width)
let height = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.height,
multiplier: 1,
constant: 0);
self.view.addConstraint(height)
}
// MARK: IBActions
@IBAction func connect(sender: AnyObject) {
// Configure access token either from server or manually.
// If the default wasn't changed, try fetching from server.
if (accessToken == "TWILIO_ACCESS_TOKEN") {
do {
accessToken = try TokenUtils.fetchToken(url: tokenUrl)
} catch {
let message = "Failed to fetch access token"
logMessage(messageText: message)
return
}
}
// Prepare local media which we will share with Room Participants.
self.prepareLocalMedia()
// Preparing the connect options with the access token that we fetched (or hardcoded).
let connectOptions = TVIConnectOptions.init(token: accessToken) { (builder) in
// Use the local media that we prepared earlier.
builder.audioTracks = self.localAudioTrack != nil ? [self.localAudioTrack!] : [TVILocalAudioTrack]()
builder.videoTracks = self.localVideoTrack != nil ? [self.localVideoTrack!] : [TVILocalVideoTrack]()
// Use the preferred audio codec
if let preferredAudioCodec = Settings.shared.audioCodec {
builder.preferredAudioCodecs = [preferredAudioCodec.rawValue]
}
// Use the preferred video codec
if let preferredVideoCodec = Settings.shared.videoCodec {
builder.preferredVideoCodecs = [preferredVideoCodec.rawValue]
}
// Use the preferred encoding parameters
if let encodingParameters = Settings.shared.getEncodingParameters() {
builder.encodingParameters = encodingParameters
}
// The name of the Room where the Client will attempt to connect to. Please note that if you pass an empty
// Room `name`, the Client will create one for you. You can get the name or sid from any connected Room.
builder.roomName = self.roomTextField.text
}
// Connect to the Room using the options we provided.
room = TwilioVideo.connect(with: connectOptions, delegate: self)
logMessage(messageText: "Attempting to connect to room \(String(describing: self.roomTextField.text))")
self.showRoomUI(inRoom: true)
self.dismissKeyboard()
}
@IBAction func disconnect(sender: AnyObject) {
self.room!.disconnect()
logMessage(messageText: "Attempting to disconnect from room \(room!.name)")
}
@IBAction func toggleMic(sender: AnyObject) {
if (self.localAudioTrack != nil) {
self.localAudioTrack?.isEnabled = !(self.localAudioTrack?.isEnabled)!
// Update the button title
if (self.localAudioTrack?.isEnabled == true) {
self.micButton.setTitle("Mute", for: .normal)
} else {
self.micButton.setTitle("Unmute", for: .normal)
}
}
}
// MARK: Private
func startPreview() {
if PlatformUtils.isSimulator {
return
}
// Preview our local camera track in the local video preview view.
camera = TVICameraCapturer(source: .frontCamera, delegate: self)
localVideoTrack = TVILocalVideoTrack.init(capturer: camera!, enabled: true, constraints: nil, name: "Camera")
if (localVideoTrack == nil) {
logMessage(messageText: "Failed to create video track")
} else {
// Add renderer to video track for local preview
localVideoTrack!.addRenderer(self.previewView)
logMessage(messageText: "Video track created")
// We will flip camera on tap.
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.flipCamera))
self.previewView.addGestureRecognizer(tap)
}
}
func flipCamera() {
if (self.camera?.source == .frontCamera) {
self.camera?.selectSource(.backCameraWide)
} else {
self.camera?.selectSource(.frontCamera)
}
}
func prepareLocalMedia() {
// We will share local audio and video when we connect to the Room.
// Create an audio track.
if (localAudioTrack == nil) {
localAudioTrack = TVILocalAudioTrack.init(options: nil, enabled: true, name: "Microphone")
if (localAudioTrack == nil) {
logMessage(messageText: "Failed to create audio track")
}
}
// Create a video track which captures from the camera.
if (localVideoTrack == nil) {
self.startPreview()
}
}
// Update our UI based upon if we are in a Room or not
func showRoomUI(inRoom: Bool) {
self.connectButton.isHidden = inRoom
self.roomTextField.isHidden = inRoom
self.roomLine.isHidden = inRoom
self.roomLabel.isHidden = inRoom
self.micButton.isHidden = !inRoom
self.disconnectButton.isHidden = !inRoom
self.navigationController?.setNavigationBarHidden(inRoom, animated: true)
UIApplication.shared.isIdleTimerDisabled = inRoom
}
func dismissKeyboard() {
if (self.roomTextField.isFirstResponder) {
self.roomTextField.resignFirstResponder()
}
}
func cleanupRemoteParticipant() {
if ((self.remoteParticipant) != nil) {
if ((self.remoteParticipant?.videoTracks.count)! > 0) {
let remoteVideoTrack = self.remoteParticipant?.remoteVideoTracks[0].remoteTrack
remoteVideoTrack?.removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
self.remoteParticipant = nil
}
func logMessage(messageText: String) {
messageLabel.text = messageText
}
}
// MARK: UITextFieldDelegate
extension ViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.connect(sender: textField)
return true
}
}
// MARK: TVIRoomDelegate
extension ViewController : TVIRoomDelegate {
func didConnect(to room: TVIRoom) {
// At the moment, this example only supports rendering one Participant at a time.
if let identity = room.localParticipant?.identity {
logMessage(messageText: "Connected to room \(room.name) as \(String(identity))")
}
if (room.remoteParticipants.count > 0) {
self.remoteParticipant = room.remoteParticipants[0]
self.remoteParticipant?.delegate = self
}
}
func room(_ room: TVIRoom, didDisconnectWithError error: Error?) {
logMessage(messageText: "Disconncted from room \(room.name), error = \(String(describing: error))")
self.cleanupRemoteParticipant()
self.room = nil
self.showRoomUI(inRoom: false)
}
func room(_ room: TVIRoom, didFailToConnectWithError error: Error) {
logMessage(messageText: "Failed to connect to room with error")
self.room = nil
self.showRoomUI(inRoom: false)
}
func room(_ room: TVIRoom, participantDidConnect participant: TVIRemoteParticipant) {
if (self.remoteParticipant == nil) {
self.remoteParticipant = participant
self.remoteParticipant?.delegate = self
}
logMessage(messageText: "Participant \(participant.identity) connected with \(participant.remoteAudioTracks.count) audio and \(participant.remoteVideoTracks.count) video tracks")
}
func room(_ room: TVIRoom, participantDidDisconnect participant: TVIRemoteParticipant) {
if (self.remoteParticipant == participant) {
cleanupRemoteParticipant()
}
logMessage(messageText: "Room \(room.name), Participant \(participant.identity) disconnected")
}
}
// MARK: TVIRemoteParticipantDelegate
extension ViewController : TVIRemoteParticipantDelegate {
func remoteParticipant(_ participant: TVIRemoteParticipant,
publishedVideoTrack publication: TVIRemoteVideoTrackPublication) {
// Remote Participant has offered to share the video Track.
logMessage(messageText: "Participant \(participant.identity) published \(publication.trackName) video track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
unpublishedVideoTrack publication: TVIRemoteVideoTrackPublication) {
// Remote Participant has stopped sharing the video Track.
logMessage(messageText: "Participant \(participant.identity) unpublished \(publication.trackName) video track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
publishedAudioTrack publication: TVIRemoteAudioTrackPublication) {
// Remote Participant has offered to share the audio Track.
logMessage(messageText: "Participant \(participant.identity) published \(publication.trackName) audio track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
unpublishedAudioTrack publication: TVIRemoteAudioTrackPublication) {
// Remote Participant has stopped sharing the audio Track.
logMessage(messageText: "Participant \(participant.identity) unpublished \(publication.trackName) audio track")
}
func subscribed(to videoTrack: TVIRemoteVideoTrack,
publication: TVIRemoteVideoTrackPublication,
for participant: TVIRemoteParticipant) {
// We are subscribed to the remote Participant's audio Track. We will start receiving the
// remote Participant's video frames now.
logMessage(messageText: "Subscribed to \(publication.trackName) video track for Participant \(participant.identity)")
if (self.remoteParticipant == participant) {
setupRemoteVideoView()
videoTrack.addRenderer(self.remoteView!)
}
}
func unsubscribed(from videoTrack: TVIRemoteVideoTrack,
publication: TVIRemoteVideoTrackPublication,
for participant: TVIRemoteParticipant) {
// We are unsubscribed from the remote Participant's video Track. We will no longer receive the
// remote Participant's video.
logMessage(messageText: "Unsubscribed from \(publication.trackName) video track for Participant \(participant.identity)")
if (self.remoteParticipant == participant) {
videoTrack.removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
func subscribed(to audioTrack: TVIRemoteAudioTrack,
publication: TVIRemoteAudioTrackPublication,
for participant: TVIRemoteParticipant) {
// We are subscribed to the remote Participant's audio Track. We will start receiving the
// remote Participant's audio now.
logMessage(messageText: "Subscribed to \(publication.trackName) audio track for Participant \(participant.identity)")
}
func unsubscribed(from audioTrack: TVIRemoteAudioTrack,
publication: TVIRemoteAudioTrackPublication,
for participant: TVIRemoteParticipant) {
// We are unsubscribed from the remote Participant's audio Track. We will no longer receive the
// remote Participant's audio.
logMessage(messageText: "Unsubscribed from \(publication.trackName) audio track for Participant \(participant.identity)")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
enabledVideoTrack publication: TVIRemoteVideoTrackPublication) {
logMessage(messageText: "Participant \(participant.identity) enabled \(publication.trackName) video track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
disabledVideoTrack publication: TVIRemoteVideoTrackPublication) {
logMessage(messageText: "Participant \(participant.identity) disabled \(publication.trackName) video track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
enabledAudioTrack publication: TVIRemoteAudioTrackPublication) {
logMessage(messageText: "Participant \(participant.identity) enabled \(publication.trackName) audio track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
disabledAudioTrack publication: TVIRemoteAudioTrackPublication) {
logMessage(messageText: "Participant \(participant.identity) disabled \(publication.trackName) audio track")
}
func failedToSubscribe(toAudioTrack publication: TVIRemoteAudioTrackPublication,
error: Error,
for participant: TVIRemoteParticipant) {
logMessage(messageText: "FailedToSubscribe \(publication.trackName) audio track, error = \(String(describing: error))")
}
func failedToSubscribe(toVideoTrack publication: TVIRemoteVideoTrackPublication,
error: Error,
for participant: TVIRemoteParticipant) {
logMessage(messageText: "FailedToSubscribe \(publication.trackName) video track, error = \(String(describing: error))")
}
}
// MARK: TVIVideoViewDelegate
extension ViewController : TVIVideoViewDelegate {
func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) {
self.view.setNeedsLayout()
}
}
// MARK: TVICameraCapturerDelegate
extension ViewController : TVICameraCapturerDelegate {
func cameraCapturer(_ capturer: TVICameraCapturer, didStartWith source: TVICameraCaptureSource) {
self.previewView.shouldMirror = (source == .frontCamera)
}
}