forked from twilio/video-quickstart-ios
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ViewController+CallKit.swift
212 lines (164 loc) · 7.44 KB
/
ViewController+CallKit.swift
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
//
// ViewController+CallKit.swift
// VideoCallKitQuickStart
//
// Copyright © 2016-2017 Twilio, Inc. All rights reserved.
//
import UIKit
import TwilioVideo
import CallKit
import AVFoundation
extension ViewController : CXProviderDelegate {
func providerDidReset(_ provider: CXProvider) {
logMessage(messageText: "providerDidReset:")
TVIAudioController.shared().stopAudio()
room?.disconnect()
}
func providerDidBegin(_ provider: CXProvider) {
logMessage(messageText: "providerDidBegin")
}
func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
logMessage(messageText: "provider:didActivateAudioSession:")
TVIAudioController.shared().startAudio()
}
func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
logMessage(messageText: "provider:didDeactivateAudioSession:")
}
func provider(_ provider: CXProvider, timedOutPerforming action: CXAction) {
logMessage(messageText: "provider:timedOutPerformingAction:")
}
func provider(_ provider: CXProvider, perform action: CXStartCallAction) {
logMessage(messageText: "provider:performStartCallAction:")
/*
* Configure the audio session, but do not start call audio here, since it must be done once
* the audio session has been activated by the system after having its priority elevated.
*/
TVIAudioController.shared().configureAudioSession(.videoChatSpeaker)
callKitProvider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: nil)
performRoomConnect(uuid: action.callUUID, roomName: action.handle.value) { (success) in
if (success) {
provider.reportOutgoingCall(with: action.callUUID, connectedAt: Date())
action.fulfill()
} else {
action.fail()
}
}
}
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
logMessage(messageText: "provider:performAnswerCallAction:")
/*
* Configure the audio session, but do not start call audio here, since it must be done once
* the audio session has been activated by the system after having its priority elevated.
*/
TVIAudioController.shared().configureAudioSession(.videoChatSpeaker)
performRoomConnect(uuid: action.callUUID, roomName: self.roomTextField.text) { (success) in
if (success) {
action.fulfill(withDateConnected: Date())
} else {
action.fail()
}
}
}
func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
NSLog("provider:performEndCallAction:")
TVIAudioController.shared().stopAudio()
room?.disconnect()
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {
NSLog("provier:performSetMutedCallAction:")
toggleMic(sender: self)
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
NSLog("provier:performSetHeldCallAction:")
let cxObserver = callKitCallController.callObserver
let calls = cxObserver.calls
guard let call = calls.first(where:{$0.uuid == action.callUUID}) else {
action.fail()
return
}
if call.isOnHold {
holdCall(onHold: false)
} else {
holdCall(onHold: true)
}
action.fulfill()
}
}
// MARK: Call Kit Actions
extension ViewController {
func performStartCallAction(uuid: UUID, roomName: String?) {
let callHandle = CXHandle(type: .generic, value: roomName ?? "")
let startCallAction = CXStartCallAction(call: uuid, handle: callHandle)
startCallAction.isVideo = true
let transaction = CXTransaction(action: startCallAction)
callKitCallController.request(transaction) { error in
if let error = error {
NSLog("StartCallAction transaction request failed: \(error.localizedDescription)")
return
}
NSLog("StartCallAction transaction request successful")
}
}
func reportIncomingCall(uuid: UUID, roomName: String?, completion: ((NSError?) -> Void)? = nil) {
let callHandle = CXHandle(type: .generic, value: roomName ?? "")
let callUpdate = CXCallUpdate()
callUpdate.remoteHandle = callHandle
callUpdate.supportsDTMF = false
callUpdate.supportsHolding = true
callUpdate.supportsGrouping = false
callUpdate.supportsUngrouping = false
callUpdate.hasVideo = true
callKitProvider.reportNewIncomingCall(with: uuid, update: callUpdate) { error in
if error == nil {
NSLog("Incoming call successfully reported.")
} else {
NSLog("Failed to report incoming call successfully: \(String(describing: error?.localizedDescription)).")
}
completion?(error as NSError?)
}
}
func performEndCallAction(uuid: UUID) {
let endCallAction = CXEndCallAction(call: uuid)
let transaction = CXTransaction(action: endCallAction)
callKitCallController.request(transaction) { error in
if let error = error {
NSLog("EndCallAction transaction request failed: \(error.localizedDescription).")
return
}
NSLog("EndCallAction transaction request successful")
}
}
func performRoomConnect(uuid: UUID, roomName: String? , completionHandler: @escaping (Bool) -> Swift.Void) {
// 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]()
// 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 = roomName
// The CallKit UUID to assoicate with this Room.
builder.uuid = uuid
}
// 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: roomName))")
self.showRoomUI(inRoom: true)
self.callKitCompletionHandler = completionHandler
}
}