-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSwitchChannel.swift
280 lines (243 loc) · 12.3 KB
/
QuickSwitchChannel.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
//
// JoinChannelVC.swift
// APIExample
//
// Created by 张乾泽 on 2020/4/17.
// Copyright © 2020 Agora Corp. All rights reserved.
//
import UIKit
import AGEVideoLayout
import AgoraRtcKit
struct ChannelInfo {
let channelName: String
}
extension ChannelInfo {
/// static function to generate 4 channels based on given channel name
static func AllChannelList(_ channelName:String) -> [ChannelInfo] {
var channels = [ChannelInfo]()
for index in 1..<5 {
let channel = ChannelInfo(
channelName: "\(channelName)\(index)"
)
channels.append(channel)
}
return channels
}
}
class QuickSwitchChannel: BaseViewController {
var pageViewController: UIPageViewController!
var channels = [ChannelInfo]()
var currentIndex = 0
var hostView: UIView?
var hostChannel: ChannelInfo?
var agoraKit: AgoraRtcEngineKit!
// indicate if current instance has joined channel
var isJoined: Bool = false
/// setup page controller, it will auto generates 4 channels with corresponding view controllers for you to swipe, every time you swipe to a new viewcontroller it will switch to that channel
func setupPageController(channelName: String) {
// generate all channel infos
channels = ChannelInfo.AllChannelList(channelName)
pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pageViewController.delegate = self
if let vc = channelViewController(at: currentIndex) {
pageViewController.setViewControllers([vc], direction: .forward, animated: false, completion: nil)
// there is only 1 rtc engine instance
// We will have to mark the current active view controller video renderer, so that we can use it in later didJoinedOfUser events
// setHostViewController grabs the hostRenderView from current active view controller, and store it in hostView property
setHostViewController(vc)
}
pageViewController.dataSource = self
// add page view controller as child view controller
addChild(pageViewController)
view.addSubview(pageViewController.view)
pageViewController!.view.frame = view.bounds
pageViewController.didMove(toParent: self)
// Add the page view controller's gesture recognizers to the view controller's view so that the gestures are started more easily.
view.gestureRecognizers = pageViewController.gestureRecognizers
}
func setHostViewController(_ viewController: QuickSwitchChannelVCItem) {
hostChannel = viewController.channel
hostView = viewController.hostRenderView
// every time we switch a view controller, we will rejoin the channel by calling switchChannel, so we always call showLoading
viewController.showLoading(true)
}
override func viewDidLoad() {
super.viewDidLoad()
// set up agora instance when view loadedlet config = AgoraRtcEngineConfig()
let config = AgoraRtcEngineConfig()
config.appId = KeyCenter.AppId
config.areaCode = GlobalSettings.shared.area.rawValue
// setup log file path
let logConfig = AgoraLogConfig()
logConfig.level = .info
config.logConfig = logConfig
agoraKit = AgoraRtcEngineKit.sharedEngine(with: config, delegate: self)
// get channel name from configs
guard let channelName = configs["channelName"] as? String else {return}
// setup UIPageController for swipe changing vc
setupPageController(channelName:channelName)
// enable video module
agoraKit.enableVideo()
// make myself an audience
agoraKit.setChannelProfile(.liveBroadcasting)
agoraKit.setClientRole(.audience)
// Set audio route to speaker
agoraKit.setDefaultAudioRouteToSpeakerphone(true)
// start joining channel
// 1. Users can only see each other after they join the
// same channel successfully using the same app id.
// 2. If app certificate is turned on at dashboard, token is needed
// when joining channel. The channel name and uid used to calculate
// the token has to match the ones used for channel join
let option = AgoraRtcChannelMediaOptions()
let result = agoraKit.joinChannel(byToken: KeyCenter.Token, channelId: channels[currentIndex].channelName, info: nil, uid: 0, options: option)
if result != 0 {
// Usually happens with invalid parameters
// Error code description can be found at:
// en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html
// cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html
self.showAlert(title: "Error", message: "joinChannel call failed: \(result), please check your params")
}
}
override func willMove(toParent parent: UIViewController?) {
if parent == nil {
// leave channel when exiting the view
if isJoined {
agoraKit.leaveChannel { (stats) -> Void in
LogUtils.log(message: "left channel, duration: \(stats.duration)", level: .info)
}
}
}
}
}
/// agora rtc engine delegate events
extension QuickSwitchChannel: AgoraRtcEngineDelegate {
/// callback when current user join channel successfully
/// @param channel channel name
/// @param uid my uid
/// @param elapsed elapsed time since joinChannel is called
func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int) {
self.isJoined = true
LogUtils.log(message: "Join \(channel) with uid \(uid) elapsed \(elapsed)ms", level: .info)
// check if the callback should be responding
guard let currentVC = pageViewController.viewControllers?.first as? QuickSwitchChannelVCItem,
currentVC.channel.channelName == channel else {
return
}
// hide loading
currentVC.showLoading(false)
}
/// callback when warning occured for agora sdk, warning can usually be ignored, still it's nice to check out
/// what is happening
/// Warning code description can be found at:
/// en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraWarningCode.html
/// cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraWarningCode.html
/// @param warningCode warning code of the problem
func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurWarning warningCode: AgoraWarningCode) {
LogUtils.log(message: "warning: \(warningCode.description)", level: .warning)
}
/// callback when error occured for agora sdk, you are recommended to display the error descriptions on demand
/// to let user know something wrong is happening
/// Error code description can be found at:
/// en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html
/// cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html
/// @param errorCode error code of the problem
func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurError errorCode: AgoraErrorCode) {
LogUtils.log(message: "error: \(errorCode)", level: .error)
self.showAlert(title: "Error", message: "Error \(errorCode.description) occur")
}
/// callback when a remote user is joinning the channel, note audience in live broadcast mode will NOT trigger this event
/// @param uid uid of remote joined user
/// @param elapsed time elapse since current sdk instance join the channel in ms
func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) {
LogUtils.log(message: "remote user join: \(uid) \(elapsed)ms", level: .info)
// check if the callback should be responding
guard let currentVC = pageViewController.viewControllers?.first as? QuickSwitchChannelVCItem,
currentVC.channel.channelName == hostChannel?.channelName else {
return
}
// Only one remote video view is available for this
// tutorial. Here we check if there exists a surface
// view tagged as this uid.
let videoCanvas = AgoraRtcVideoCanvas()
videoCanvas.uid = uid
// the view to be binded
videoCanvas.view = hostView
videoCanvas.renderMode = .hidden
agoraKit.setupRemoteVideo(videoCanvas)
}
/// callback when a remote user is leaving the channel, note audience in live broadcast mode will NOT trigger this event
/// @param uid uid of remote joined user
/// @param reason reason why this user left, note this event may be triggered when the remote user
/// become an audience in live broadcasting profile
func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) {
LogUtils.log(message: "remote user left: \(uid) reason \(reason)", level: .info)
// check if the callback should be responding
guard let currentVC = pageViewController.viewControllers?.first as? QuickSwitchChannelVCItem,
currentVC.channel.channelName == hostChannel?.channelName else {
return
}
// to unlink your view from sdk, so that your view reference will be released
// note the video will stay at its last frame, to completely remove it
// you will need to remove the EAGL sublayer from your binded view
let videoCanvas = AgoraRtcVideoCanvas()
videoCanvas.uid = uid
// the view to be binded
videoCanvas.view = nil
videoCanvas.renderMode = .hidden
agoraKit.setupRemoteVideo(videoCanvas)
}
}
private extension QuickSwitchChannel {
/// api to generate QuickSwitchChannelVCItem on demand
func channelViewController(at index: Int) -> QuickSwitchChannelVCItem? {
guard channels.count > 0 else {
return nil
}
var vcIndex = index
// if vcIndex exceeds maximum, reset to 0
if vcIndex >= channels.count {
vcIndex = 0
// else if vcIndex < 0, reset to last value
} else if vcIndex < 0 {
vcIndex = channels.count - 1
}
// create the view controller with info
let channelVC = QuickSwitchChannelVCItem(nibName: "QuickSwitchChannelVCItem", bundle: nil)
channelVC.index = vcIndex
channelVC.channel = channels[vcIndex]
return channelVC
}
}
/// Page View Controller DataSource
extension QuickSwitchChannel: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let channelVC = viewController as? QuickSwitchChannelVCItem else {
return nil
}
// return next VC
return channelViewController(at: channelVC.index + 1)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let channelVC = viewController as? QuickSwitchChannelVCItem else {
return nil
}
// return prev VC
return channelViewController(at: channelVC.index - 1)
}
}
/// Page View Controller Delegate
extension QuickSwitchChannel : UIPageViewControllerDelegate
{
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
guard let previousVC = previousViewControllers.last as? QuickSwitchChannelVCItem,
let currentVC = pageViewController.viewControllers?.first as? QuickSwitchChannelVCItem,
previousVC != currentVC else {
return
}
// switch to currentVC and its hosted channel
setHostViewController(currentVC)
let option = AgoraRtcChannelMediaOptions()
agoraKit.switchChannel(byToken: nil, channelId: currentVC.channel.channelName, options: option)
}
}