-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathViewController.swift
856 lines (679 loc) · 30.2 KB
/
ViewController.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
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//
// ViewController.swift
// Twilio Voice Quickstart - Swift
//
// Copyright © 2016 Twilio, Inc. All rights reserved.
//
import UIKit
import AVFoundation
import PushKit
import CallKit
import TwilioVoice
let accessToken = <#PASTE YOUR ACCESS TOKEN HERE#>
let twimlParamTo = "to"
let kRegistrationTTLInDays = 365
let kCachedDeviceToken = "CachedDeviceToken"
let kCachedBindingDate = "CachedBindingDate"
class ViewController: UIViewController {
@IBOutlet weak var qualityWarningsToaster: UILabel!
@IBOutlet weak var placeCallButton: UIButton!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var outgoingValue: UITextField!
@IBOutlet weak var callControlView: UIView!
@IBOutlet weak var muteSwitch: UISwitch!
@IBOutlet weak var speakerSwitch: UISwitch!
var incomingPushCompletionCallback: (() -> Void)?
var isSpinning: Bool
var incomingAlertController: UIAlertController?
var callKitCompletionCallback: ((Bool) -> Void)? = nil
var audioDevice = DefaultAudioDevice()
var activeCallInvites: [String: CallInvite]! = [:]
var activeCalls: [String: Call]! = [:]
// activeCall represents the last connected call
var activeCall: Call? = nil
var callKitProvider: CXProvider?
let callKitCallController = CXCallController()
var userInitiatedDisconnect: Bool = false
/*
Custom ringback will be played when this flag is enabled.
When [answerOnBridge](https://www.twilio.com/docs/voice/twiml/dial#answeronbridge) is enabled in
the <Dial> TwiML verb, the caller will not hear the ringback while the call is ringing and awaiting
to be accepted on the callee's side. Configure this flag based on the TwiML application.
*/
var playCustomRingback = false
var ringtonePlayer: AVAudioPlayer? = nil
required init?(coder aDecoder: NSCoder) {
isSpinning = false
super.init(coder: aDecoder)
}
deinit {
// CallKit has an odd API contract where the developer must call invalidate or the CXProvider is leaked.
if let provider = callKitProvider {
provider.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
toggleUIState(isEnabled: true, showCallControl: false)
outgoingValue.delegate = self
/* Please note that the designated initializer `CXProviderConfiguration(localizedName: String)` has been deprecated on iOS 14. */
let configuration = CXProviderConfiguration(localizedName: "Voice Quickstart")
configuration.maximumCallGroups = 2
configuration.maximumCallsPerCallGroup = 1
callKitProvider = CXProvider(configuration: configuration)
if let provider = callKitProvider {
provider.setDelegate(self, queue: nil)
}
/*
* The important thing to remember when providing a TVOAudioDevice is that the device must be set
* before performing any other actions with the SDK (such as connecting a Call, or accepting an incoming Call).
* In this case we've already initialized our own `TVODefaultAudioDevice` instance which we will now set.
*/
TwilioVoiceSDK.audioDevice = audioDevice
/* Example usage of Default logger to print app logs */
let defaultLogger = TwilioVoiceSDK.logger
if let params = LogParameters.init(module:TwilioVoiceSDK.LogModule.platform , logLevel: TwilioVoiceSDK.LogLevel.debug, message: "The default logger is used for app logs") {
defaultLogger.log(params: params)
}
}
func toggleUIState(isEnabled: Bool, showCallControl: Bool) {
placeCallButton.isEnabled = isEnabled
if showCallControl {
callControlView.isHidden = false
muteSwitch.isOn = getActiveCall()?.isMuted ?? false
for output in AVAudioSession.sharedInstance().currentRoute.outputs {
speakerSwitch.isOn = output.portType == AVAudioSessionPortBuiltInSpeaker
}
} else {
callControlView.isHidden = true
}
}
func showMicrophoneAccessRequest(_ uuid: UUID, _ handle: String) {
let alertController = UIAlertController(title: "Voice Quick Start",
message: "Microphone permission not granted",
preferredStyle: .alert)
let continueWithoutMic = UIAlertAction(title: "Continue without microphone", style: .default) { [weak self] _ in
self?.performStartCallAction(uuid: uuid, handle: handle)
}
let goToSettings = UIAlertAction(title: "Settings", style: .default) { _ in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!,
options: [UIApplicationOpenURLOptionUniversalLinksOnly: false],
completionHandler: nil)
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { [weak self] _ in
self?.toggleUIState(isEnabled: true, showCallControl: false)
self?.stopSpin()
}
[continueWithoutMic, goToSettings, cancel].forEach { alertController.addAction($0) }
present(alertController, animated: true, completion: nil)
}
func getActiveCall() -> Call? {
if let activeCall = activeCall {
return activeCall
} else if activeCalls.count == 1 {
// This is a scenario when the only remaining call is still on hold after the previous call has ended
return activeCalls.first?.value
} else {
return nil
}
}
@IBAction func mainButtonPressed(_ sender: Any) {
if !activeCalls.isEmpty {
guard let activeCall = getActiveCall() else { return }
userInitiatedDisconnect = true
performEndCallAction(uuid: activeCall.uuid!)
return
}
checkRecordPermission { [weak self] permissionGranted in
let uuid = UUID()
let handle = "Voice Bot"
guard !permissionGranted else {
self?.performStartCallAction(uuid: uuid, handle: handle)
return
}
DispatchQueue.main.async {
self?.showMicrophoneAccessRequest(uuid, handle)
}
}
}
func checkRecordPermission(completion: @escaping (_ permissionGranted: Bool) -> Void) {
let permissionStatus = AVAudioSession.sharedInstance().recordPermission()
switch permissionStatus {
case .granted:
// Record permission already granted.
completion(true)
case .denied:
// Record permission denied.
completion(false)
case .undetermined:
// Requesting record permission.
// Optional: pop up app dialog to let the users know if they want to request.
AVAudioSession.sharedInstance().requestRecordPermission { granted in completion(granted) }
default:
completion(false)
}
}
@IBAction func muteSwitchToggled(_ sender: UISwitch) {
guard let activeCall = getActiveCall() else { return }
activeCall.isMuted = sender.isOn
}
@IBAction func speakerSwitchToggled(_ sender: UISwitch) {
toggleAudioRoute(toSpeaker: sender.isOn)
}
// MARK: AVAudioSession
func toggleAudioRoute(toSpeaker: Bool) {
// The mode set by the Voice SDK is "VoiceChat" so the default audio route is the built-in receiver. Use port override to switch the route.
audioDevice.block = {
do {
if toSpeaker {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
} else {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)
}
} catch {
NSLog(error.localizedDescription)
}
}
audioDevice.block()
}
// MARK: Icon spinning
func startSpin() {
guard !isSpinning else { return }
isSpinning = true
spin(options: UIViewAnimationOptions.curveEaseIn)
}
func stopSpin() {
isSpinning = false
}
func spin(options: UIViewAnimationOptions) {
UIView.animate(withDuration: 0.5, delay: 0.0, options: options, animations: { [weak iconView] in
if let iconView = iconView {
iconView.transform = iconView.transform.rotated(by: CGFloat(Double.pi/2))
}
}) { [weak self] finished in
guard let strongSelf = self else { return }
if finished {
if strongSelf.isSpinning {
strongSelf.spin(options: UIViewAnimationOptions.curveLinear)
} else if options != UIViewAnimationOptions.curveEaseOut {
strongSelf.spin(options: UIViewAnimationOptions.curveEaseOut)
}
}
}
}
}
// MARK: - UITextFieldDelegate
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
outgoingValue.resignFirstResponder()
return true
}
}
// MARK: - PushKitEventDelegate
extension ViewController: PushKitEventDelegate {
func credentialsUpdated(credentials: PKPushCredentials) {
guard
(registrationRequired() || UserDefaults.standard.data(forKey: kCachedDeviceToken) != credentials.token)
else {
return
}
let cachedDeviceToken = credentials.token
/*
* Perform registration if a new device token is detected.
*/
TwilioVoiceSDK.register(accessToken: accessToken, deviceToken: cachedDeviceToken) { error in
if let error = error {
NSLog("An error occurred while registering: \(error.localizedDescription)")
} else {
NSLog("Successfully registered for VoIP push notifications.")
// Save the device token after successfully registered.
UserDefaults.standard.set(cachedDeviceToken, forKey: kCachedDeviceToken)
/**
* The TTL of a registration is 1 year. The TTL for registration for this device/identity
* pair is reset to 1 year whenever a new registration occurs or a push notification is
* sent to this device/identity pair.
*/
UserDefaults.standard.set(Date(), forKey: kCachedBindingDate)
}
}
}
/**
* The TTL of a registration is 1 year. The TTL for registration for this device/identity pair is reset to
* 1 year whenever a new registration occurs or a push notification is sent to this device/identity pair.
* This method checks if binding exists in UserDefaults, and if half of TTL has been passed then the method
* will return true, else false.
*/
func registrationRequired() -> Bool {
guard
let lastBindingCreated = UserDefaults.standard.object(forKey: kCachedBindingDate)
else { return true }
let date = Date()
var components = DateComponents()
components.setValue(kRegistrationTTLInDays/2, for: .day)
let expirationDate = Calendar.current.date(byAdding: components, to: lastBindingCreated as! Date)!
if expirationDate.compare(date) == ComparisonResult.orderedDescending {
return false
}
return true;
}
func credentialsInvalidated() {
guard let deviceToken = UserDefaults.standard.data(forKey: kCachedDeviceToken) else { return }
TwilioVoiceSDK.unregister(accessToken: accessToken, deviceToken: deviceToken) { error in
if let error = error {
NSLog("An error occurred while unregistering: \(error.localizedDescription)")
} else {
NSLog("Successfully unregistered from VoIP push notifications.")
}
}
UserDefaults.standard.removeObject(forKey: kCachedDeviceToken)
// Remove the cached binding as credentials are invalidated
UserDefaults.standard.removeObject(forKey: kCachedBindingDate)
}
func incomingPushReceived(payload: PKPushPayload) {
// The Voice SDK will use main queue to invoke `cancelledCallInviteReceived:error:` when delegate queue is not passed
TwilioVoiceSDK.handleNotification(payload.dictionaryPayload, delegate: self, delegateQueue: nil)
}
func incomingPushReceived(payload: PKPushPayload, completion: @escaping () -> Void) {
// The Voice SDK will use main queue to invoke `cancelledCallInviteReceived:error:` when delegate queue is not passed
TwilioVoiceSDK.handleNotification(payload.dictionaryPayload, delegate: self, delegateQueue: nil)
if let version = Float(UIDevice.current.systemVersion), version < 13.0 {
// Save for later when the notification is properly handled.
incomingPushCompletionCallback = completion
}
}
func incomingPushHandled() {
guard let completion = incomingPushCompletionCallback else { return }
incomingPushCompletionCallback = nil
completion()
}
}
// MARK: - TVONotificaitonDelegate
extension ViewController: NotificationDelegate {
func callInviteReceived(callInvite: CallInvite) {
NSLog("callInviteReceived:")
/**
* The TTL of a registration is 1 year. The TTL for registration for this device/identity
* pair is reset to 1 year whenever a new registration occurs or a push notification is
* sent to this device/identity pair.
*/
UserDefaults.standard.set(Date(), forKey: kCachedBindingDate)
let callerInfo: TVOCallerInfo = callInvite.callerInfo
if let verified: NSNumber = callerInfo.verified {
if verified.boolValue {
NSLog("Call invite received from verified caller number!")
}
}
let from = (callInvite.from ?? "Voice Bot").replacingOccurrences(of: "client:", with: "")
// Always report to CallKit
reportIncomingCall(from: from, uuid: callInvite.uuid)
activeCallInvites[callInvite.uuid.uuidString] = callInvite
}
func cancelledCallInviteReceived(cancelledCallInvite: CancelledCallInvite, error: Error) {
NSLog("cancelledCallInviteCanceled:error:, error: \(error.localizedDescription)")
guard let activeCallInvites = activeCallInvites, !activeCallInvites.isEmpty else {
NSLog("No pending call invite")
return
}
let callInvite = activeCallInvites.values.first { invite in invite.callSid == cancelledCallInvite.callSid }
if let callInvite = callInvite {
performEndCallAction(uuid: callInvite.uuid)
self.activeCallInvites.removeValue(forKey: callInvite.uuid.uuidString)
}
}
}
// MARK: - TVOCallDelegate
extension ViewController: CallDelegate {
func callDidStartRinging(call: Call) {
NSLog("callDidStartRinging:")
placeCallButton.setTitle("Ringing", for: .normal)
/*
When [answerOnBridge](https://www.twilio.com/docs/voice/twiml/dial#answeronbridge) is enabled in the
<Dial> TwiML verb, the caller will not hear the ringback while the call is ringing and awaiting to be
accepted on the callee's side. The application can use the `AVAudioPlayer` to play custom audio files
between the `[TVOCallDelegate callDidStartRinging:]` and the `[TVOCallDelegate callDidConnect:]` callbacks.
*/
if playCustomRingback {
playRingback()
}
}
func callDidConnect(call: Call) {
NSLog("callDidConnect:")
if playCustomRingback {
stopRingback()
}
if let callKitCompletionCallback = callKitCompletionCallback {
callKitCompletionCallback(true)
}
placeCallButton.setTitle("Hang Up", for: .normal)
stopSpin()
toggleAudioRoute(toSpeaker: true)
toggleUIState(isEnabled: true, showCallControl: true)
}
func callIsReconnecting(call: Call, error: Error) {
NSLog("call:isReconnectingWithError:")
placeCallButton.setTitle("Reconnecting", for: .normal)
toggleUIState(isEnabled: false, showCallControl: false)
}
func callDidReconnect(call: Call) {
NSLog("callDidReconnect:")
placeCallButton.setTitle("Hang Up", for: .normal)
toggleUIState(isEnabled: true, showCallControl: true)
}
func callDidFailToConnect(call: Call, error: Error) {
NSLog("Call failed to connect: \(error.localizedDescription)")
if let completion = callKitCompletionCallback {
completion(false)
}
if let provider = callKitProvider {
provider.reportCall(with: call.uuid!, endedAt: Date(), reason: CXCallEndedReason.failed)
}
callDisconnected(call: call)
}
func callDidDisconnect(call: Call, error: Error?) {
if let error = error {
NSLog("Call failed: \(error.localizedDescription)")
} else {
NSLog("Call disconnected")
}
if !userInitiatedDisconnect {
var reason = CXCallEndedReason.remoteEnded
if error != nil {
reason = .failed
}
if let provider = callKitProvider {
provider.reportCall(with: call.uuid!, endedAt: Date(), reason: reason)
}
}
callDisconnected(call: call)
}
func callDisconnected(call: Call) {
if call == activeCall {
activeCall = nil
}
activeCalls.removeValue(forKey: call.uuid!.uuidString)
userInitiatedDisconnect = false
if playCustomRingback {
stopRingback()
}
stopSpin()
if activeCalls.isEmpty {
toggleUIState(isEnabled: true, showCallControl: false)
placeCallButton.setTitle("Call", for: .normal)
} else {
guard let activeCall = getActiveCall() else { return }
toggleUIState(isEnabled: true, showCallControl: true)
}
}
func callDidReceiveQualityWarnings(call: Call, currentWarnings: Set<NSNumber>, previousWarnings: Set<NSNumber>) {
/**
* currentWarnings: existing quality warnings that have not been cleared yet
* previousWarnings: last set of warnings prior to receiving this callback
*
* Example:
* - currentWarnings: { A, B }
* - previousWarnings: { B, C }
* - intersection: { B }
*
* Newly raised warnings = currentWarnings - intersection = { A }
* Newly cleared warnings = previousWarnings - intersection = { C }
*/
var warningsIntersection: Set<NSNumber> = currentWarnings
warningsIntersection = warningsIntersection.intersection(previousWarnings)
var newWarnings: Set<NSNumber> = currentWarnings
newWarnings.subtract(warningsIntersection)
if newWarnings.count > 0 {
qualityWarningsUpdatePopup(newWarnings, isCleared: false)
}
var clearedWarnings: Set<NSNumber> = previousWarnings
clearedWarnings.subtract(warningsIntersection)
if clearedWarnings.count > 0 {
qualityWarningsUpdatePopup(clearedWarnings, isCleared: true)
}
}
func qualityWarningsUpdatePopup(_ warnings: Set<NSNumber>, isCleared: Bool) {
var popupMessage: String = "Warnings detected: "
if isCleared {
popupMessage = "Warnings cleared: "
}
let mappedWarnings: [String] = warnings.map { number in warningString(Call.QualityWarning(rawValue: number.uintValue)!)}
popupMessage += mappedWarnings.joined(separator: ", ")
qualityWarningsToaster.alpha = 0.0
qualityWarningsToaster.text = popupMessage
UIView.animate(withDuration: 1.0, animations: {
self.qualityWarningsToaster.isHidden = false
self.qualityWarningsToaster.alpha = 1.0
}) { [weak self] finish in
guard let strongSelf = self else { return }
let deadlineTime = DispatchTime.now() + .seconds(5)
DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: {
UIView.animate(withDuration: 1.0, animations: {
strongSelf.qualityWarningsToaster.alpha = 0.0
}) { (finished) in
strongSelf.qualityWarningsToaster.isHidden = true
}
})
}
}
func warningString(_ warning: Call.QualityWarning) -> String {
switch warning {
case .highRtt: return "high-rtt"
case .highJitter: return "high-jitter"
case .highPacketsLostFraction: return "high-packets-lost-fraction"
case .lowMos: return "low-mos"
case .constantAudioInputLevel: return "constant-audio-input-level"
default: return "Unknown warning"
}
}
// MARK: Ringtone
func playRingback() {
let ringtonePath = URL(fileURLWithPath: Bundle.main.path(forResource: "ringtone", ofType: "wav")!)
do {
ringtonePlayer = try AVAudioPlayer(contentsOf: ringtonePath)
ringtonePlayer?.delegate = self
ringtonePlayer?.numberOfLoops = -1
ringtonePlayer?.volume = 1.0
ringtonePlayer?.play()
} catch {
NSLog("Failed to initialize audio player")
}
}
func stopRingback() {
guard let ringtonePlayer = ringtonePlayer, ringtonePlayer.isPlaying else { return }
ringtonePlayer.stop()
}
}
// MARK: - CXProviderDelegate
extension ViewController: CXProviderDelegate {
func providerDidReset(_ provider: CXProvider) {
NSLog("providerDidReset:")
audioDevice.isEnabled = false
}
func providerDidBegin(_ provider: CXProvider) {
NSLog("providerDidBegin")
}
func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
NSLog("provider:didActivateAudioSession:")
audioDevice.isEnabled = true
}
func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
NSLog("provider:didDeactivateAudioSession:")
audioDevice.isEnabled = false
}
func provider(_ provider: CXProvider, timedOutPerforming action: CXAction) {
NSLog("provider:timedOutPerformingAction:")
}
func provider(_ provider: CXProvider, perform action: CXStartCallAction) {
NSLog("provider:performStartCallAction:")
toggleUIState(isEnabled: false, showCallControl: false)
startSpin()
provider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: Date())
performVoiceCall(uuid: action.callUUID, client: "") { success in
if success {
NSLog("performVoiceCall() successful")
provider.reportOutgoingCall(with: action.callUUID, connectedAt: Date())
} else {
NSLog("performVoiceCall() failed")
}
}
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
NSLog("provider:performAnswerCallAction:")
performAnswerVoiceCall(uuid: action.callUUID) { success in
if success {
NSLog("performAnswerVoiceCall() successful")
} else {
NSLog("performAnswerVoiceCall() failed")
}
}
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
NSLog("provider:performEndCallAction:")
if let invite = activeCallInvites[action.callUUID.uuidString] {
invite.reject()
activeCallInvites.removeValue(forKey: action.callUUID.uuidString)
} else if let call = activeCalls[action.callUUID.uuidString] {
call.disconnect()
} else {
NSLog("Unknown UUID to perform end-call action with")
}
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
NSLog("provider:performSetHeldAction:")
if let call = activeCalls[action.callUUID.uuidString] {
call.isOnHold = action.isOnHold
/** Explicitly enable the TVOAudioDevice.
* This is workaround for an iOS issue where the `provider(_:didActivate:)` method is not called
* when un-holding a VoIP call after an ended PSTN call.
*/ https://developer.apple.com/forums/thread/694836
if !call.isOnHold {
audioDevice.isEnabled = true
activeCall = call
}
toggleUIState(isEnabled: true, showCallControl: true)
action.fulfill()
} else {
action.fail()
}
}
func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {
NSLog("provider:performSetMutedAction:")
if let call = activeCalls[action.callUUID.uuidString] {
call.isMuted = action.isMuted
action.fulfill()
} else {
action.fail()
}
}
func provider(_ provider: CXProvider, perform action: CXPlayDTMFCallAction) {
NSLog("provider:performPlayDTMFCallAction:")
if let call = activeCalls[action.callUUID.uuidString] {
call.sendDigits(action.digits)
action.fulfill()
} else {
action.fail()
}
}
// MARK: Call Kit Actions
func performStartCallAction(uuid: UUID, handle: String) {
guard let provider = callKitProvider else {
NSLog("CallKit provider not available")
return
}
let callHandle = CXHandle(type: .generic, value: handle)
let startCallAction = CXStartCallAction(call: uuid, handle: callHandle)
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")
let callUpdate = CXCallUpdate()
callUpdate.remoteHandle = callHandle
callUpdate.supportsDTMF = true
callUpdate.supportsHolding = true
callUpdate.supportsGrouping = false
callUpdate.supportsUngrouping = false
callUpdate.hasVideo = false
provider.reportCall(with: uuid, updated: callUpdate)
}
}
func reportIncomingCall(from: String, uuid: UUID) {
guard let provider = callKitProvider else {
NSLog("CallKit provider not available")
return
}
let callHandle = CXHandle(type: .generic, value: from)
let callUpdate = CXCallUpdate()
callUpdate.remoteHandle = callHandle
callUpdate.supportsDTMF = true
callUpdate.supportsHolding = true
callUpdate.supportsGrouping = false
callUpdate.supportsUngrouping = false
callUpdate.hasVideo = false
provider.reportNewIncomingCall(with: uuid, update: callUpdate) { error in
if let error = error {
NSLog("Failed to report incoming call successfully: \(error.localizedDescription).")
} else {
NSLog("Incoming call successfully reported.")
}
}
}
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).")
} else {
NSLog("EndCallAction transaction request successful")
}
}
}
func performVoiceCall(uuid: UUID, client: String?, completionHandler: @escaping (Bool) -> Void) {
let connectOptions = ConnectOptions(accessToken: accessToken) { builder in
builder.params = [twimlParamTo: self.outgoingValue.text ?? ""]
builder.uuid = uuid
}
let call = TwilioVoiceSDK.connect(options: connectOptions, delegate: self)
activeCall = call
activeCalls[call.uuid!.uuidString] = call
callKitCompletionCallback = completionHandler
}
func performAnswerVoiceCall(uuid: UUID, completionHandler: @escaping (Bool) -> Void) {
guard let callInvite = activeCallInvites[uuid.uuidString] else {
NSLog("No CallInvite matches the UUID")
return
}
let acceptOptions = AcceptOptions(callInvite: callInvite) { builder in
builder.uuid = callInvite.uuid
}
let call = callInvite.accept(options: acceptOptions, delegate: self)
activeCall = call
activeCalls[call.uuid!.uuidString] = call
callKitCompletionCallback = completionHandler
activeCallInvites.removeValue(forKey: uuid.uuidString)
guard #available(iOS 13, *) else {
incomingPushHandled()
return
}
}
}
// MARK: - AVAudioPlayerDelegate
extension ViewController: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if flag {
NSLog("Audio player finished playing successfully");
} else {
NSLog("Audio player finished playing with some error");
}
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
if let error = error {
NSLog("Decode error occurred: \(error.localizedDescription)")
}
}
}