IOS技术分享| any自习室场景实现

知识养成了思想,思想同时又在融化知识。这篇文章主要讲述IOS技术分享| any自习室场景实现相关的知识,希望能为你提供帮助。
前言
线上自习室,又称“在线自习室”“云自习室”“云上自习室”“云端自习室”,是一种用互联网技术打造的在线自习室。线上自习室打破了时间、空间的束缚,比线下自习室更便捷,形式更多样。anyRTC 作为全球实时音视频云服务供应商,推出了any自习室,致力于帮助开发者更快地实现实时互动场景。
场景实现
效果截屏

IOS技术分享| any自习室场景实现

文章图片

ios 体验 & 源码下载
  • 下载体验
  • 源码下载
开发环境
  • 【IOS技术分享| any自习室场景实现】开发工具:Xcode12真机运行
  • 开发语言:Swift
  • 实现:连麦互动,包含推拉流、连麦、聊天等。
SDK 集成方式
方式一:官网获取https://docs.anyrtc.io/download
方式二:CocoaPods 获取
platform :ios, \'9.0\' use_frameworks!target \'Your App\' do #anyRTC 音视频库 pod \'ARtcKit_iOS\', \'~> 4.2.2.4\' #anyRTC 实时消息库 pod \'ARtmKit_iOS\', \'~> 1.0.1.7\' end

示例代码
效果展示
IOS技术分享| any自习室场景实现

文章图片

代码实现
class RefreshGifHeader: MJRefreshHeader { var rotatingImage: UIImageView?override var state: MJRefreshState { didSet { switch state { case .idle,.pulling: rotatingImage?.stopAnimating() break case .refreshing: rotatingImage?.startAnimating() break default: print("") } } }override func prepare() { super.prepare() rotatingImage = UIImageView.init() rotatingImage?.image = UIImage(named: "icon_refresh") self.addSubview(rotatingImage!)let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnim.fromValue = https://www.songbingjia.com/android/0 rotationAnim.toValue = Double.pi * 2 rotationAnim.repeatCount = MAXFLOAT rotationAnim.duration = 1 rotationAnim.isRemovedOnCompletion = false rotatingImage!.layer.add(rotationAnim, forKey:"rotationAnimation") }override func placeSubviews() { super.placeSubviews() rotatingImage?.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40) rotatingImage?.center = CGPoint(x: self.mj_w / 2, y: self.mj_h / 2) } }class ARMainViewController: UICollectionViewController { private var flowLayout: UICollectionViewFlowLayout! private var index = 0var modelArr = [ARMainRoomListModel]()lazy var placeholder: UILabel = { let label: UILabel = UILabel() label.frame = CGRect.init(x: (collectionView.width - 200)/2, y: (collectionView.height - 218)/2, width: 200, height: 188) label.attributed.text = """ \\(.image(#imageLiteral(resourceName: "icon_nonet"), .custom(size: CGSize(width: 189, height: 141))), action: requestRoomList) \\("\\n 网络开小差了~", .foreground(UIColor(hexString: "#757575")), .font(UIFont(name: PingFang, size: 14)!), .action(requestRoomList)) """ label.numberOfLines = 0 label.textAlignment = .center return label }()override func viewDidLoad() { super.viewDidLoad() (UserDefaults.string(forKey: .uid) != nil) ? login() : registered()// Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false// Do any additional setup after loading the view. flowLayout = UICollectionViewFlowLayout.init() flowLayout.sectionInset = UIEdgeInsets(top: 15, left: 15, bottom: 0, right: 15) flowLayout?.scrollDirection = .vertical flowLayout?.minimumLineSpacing = 9 flowLayout?.minimumInteritemSpacing = 9 let width = (ARScreenWidth - 40)/2 flowLayout?.itemSize = CGSize.init(width: width, height: width * 1.529) collectionView.collectionViewLayout = flowLayout collectionView.mj_header = RefreshGifHeader(refreshingBlock: { [weak self] () -> Void in self?.requestRoomList() })self.view.addSubview(placeholder) NotificationCenter.default.addObserver(self, selector: #selector(requestRoomList), name: UIResponder.studyRoomNotificationLoginSucess, object: nil) }

实例化 SDK 对象 代码实现
private func initializeEngine() { // init ARtcEngineKit rtcKit = ARtcEngineKit.sharedEngine(withAppId: UserDefaults.string(forKey: .appid)!, delegate: self) rtcKit.setChannelProfile(.liveBroadcasting) rtcKit.enableVideo()// init ARtmKit rtmEngine = ARtmKit.init(appId: UserDefaults.string(forKey: .appid)!, delegate: self) rtmEngine.login(byToken: infoVideoModel.rtmToken, user: UserDefaults.string(forKey: .uid) ?? "0") {(errorCode) in } }func joinChannel() { let uid = UserDefaults.string(forKey: .uid) rtcKit.joinChannel(byToken: infoVideoModel.rtcToken, channelId: infoVideoModel.roomId!, uid: uid) {(channel, uid, elapsed) in print("joinChannel sucess") } }func leaveChannel() { rtcKit.leaveChannel { (stats) in print("leaveChannel") } }@objc func sendChannelMessage(text: String) { // 发送频道消息 let rtmMessage: ARtmMessage = ARtmMessage.init(text: text) let options: ARtmSendMessageOptions = ARtmSendMessageOptions() rtmChannel?.send(rtmMessage, sendMessageOptions: options) { (errorCode) in print("Send Channel Message") } }private func addOrUpdateChannel(key: String, value: String) { // 更新频道属性 let channelAttribute = ARtmChannelAttribute() channelAttribute.key = key channelAttribute.value = https://www.songbingjia.com/android/valuelet attributeOptions = ARtmChannelAttributeOptions() attributeOptions.enableNotificationToChannelMembers = truertmEngine.addOrUpdateChannel(infoVideoModel.roomId!, attributes: [channelAttribute], options: attributeOptions) { (errorCode) in print("addOrUpdateChannel code: \\(errorCode.rawValue)") } }

成员列表 效果展示
IOS技术分享| any自习室场景实现

文章图片

代码实现
class ARMemberView: UIView { fileprivate var memberArr = [ARMicModel]() fileprivate var memberWidth = appDelegate.allowRotation ? ARScreenHeight/2 : ARScreenWidth fileprivate var memberHeight = appDelegate.allowRotation ? (ARScreenWidth - 50) : (ARScreenHeight/2 - 50)fileprivate lazy var tableView: UITableView = { let tableView: UITableView = UITableView(frame: CGRect(x: 0.0, y: 0.0, width: memberWidth, height: memberHeight), style: .plain) tableView.delegate = self tableView.dataSource = self tableView.rowHeight = 52 tableView.tableFooterView = UIView() return tableView }()required init?(coder: NSCoder) { super.init(coder: coder) self.addSubview(placeholder) self.addSubview(tableView) }func reloadData() { memberArr = memberArr.sorted(by: { $0.seat < $1.seat }) tableView.isHidden = (memberArr.count == 0) tableView.reloadData() } }class ARMemberViewController: UIViewController {@IBAction func didClickMemberButton(_ sender: UIButton) { self.selectIndex = sender.tag if !sender.isSelected { let selected = broadcasterButton.isSelected broadcasterButton.isSelected = audienceButton.isSelected audienceButton.isSelected = selected changeScrollerViewContentSize() changeLinePlaceWithIndex() } }func changeScrollerViewContentSize() { UIView.animate(withDuration: 0.25) { [self] in var offset = self.scrollView.contentOffset offset.x = memberWidth * CGFloat(self.selectIndex) self.scrollView.contentOffset = offset } }func changeLinePlaceWithIndex() { UIView.animate(withDuration: 0.25) { var frame = self.lineView.frame frame.origin.x = (self.selectIndex == 0) ? self.memberWidth * 0.25 - 11 : (self.memberWidth * 0.75 - 11)self.lineView.frame = frame } } }extension ARMemberViewController: UIScrollViewDelegate {func scrollViewDidScroll(_ scrollView: UIScrollView) { selectIndex = NSInteger(scrollView.contentOffset.x / memberWidth)let selected = (selectIndex == 0) broadcasterButton.isSelected = selected audienceButton.isSelected = !selected changeLinePlaceWithIndex() } }

发送图片消息 效果展示
IOS技术分享| any自习室场景实现

文章图片

实现代码any自习室演示了如何发送图片消息,图片上传逻辑在此略过,仅做参考。
override func sendRandomImage() { // 发送图片 let imageDic = randomImage()let index = imageDic.allKeys[0] as! Int let width: CGFloat = index > 9 ? 600.0 : 400.0 let height: CGFloat = index > 9 ? 400.0 : 600.0let imageUrl: String = imageDic.allValues[0] as! String logVC?.log(logModel: ARLogModel(userName: UserDefaults.string(forKey: .userName), uid: UserDefaults.string(forKey: .uid), seat: localMicModel?.seat ?? 0, imageUrl: imageUrl, status: .image, avatar: UserDefaults.string(forKey: .avatar), imageWidth: width, imageHeight: height))let dic: NSDictionary! = ["cmd": "picMsg", "userName": UserDefaults.string(forKey: .userName) as Any, "avatar": UserDefaults.string(forKey: .avatar) as Any, "imgUrl": imageUrl, "imageWidth": width, "imageHeight": height, "setNum": localMicModel?.seat as Any] sendChannelMessage(text: getJSONStringFromDictionary(dictionary: dic)) }// MARK: - ARtmChannelDelegatefunc channel(_ channel: ARtmChannel, messageReceived message: ARtmMessage, from member: ARtmMember) { //收到频道消息回调 let dic = getDictionaryFromJSONString(jsonString: message.text) let value: String? = dic.object(forKey: "cmd") as? Stringif value =https://www.songbingjia.com/android/="picMsg" { // 图片消息 logVC?.log(logModel: ARLogModel(userName: dic.object(forKey: "userName") as? String, uid: member.uid, seat: dic.object(forKey: "setNum") as! NSInteger, imageUrl: dic .object(forKey: "imgUrl") as? String, status: .image, avatar: dic .object(forKey: "avatar") as? String, imageWidth: dic.object(forKey: "imageWidth") as! CGFloat, imageHeight: dic.object(forKey: "imageHeight") as! CGFloat)) } }

自习室信令参照表
Key Value 类型 参数 描述
cmd enterTip 频道消息 userName(string)、avatar(string) 进入房间提示消息
cmd leaveTip 频道消息 userName(string)、avatar(string) 离开房间提示消息
cmd hostTip 频道消息 userName(string) xx成为主持人
cmd msg 频道消息 content(string),userName(string)、avatar(string)、setNum(NSNumber,不在麦上0,麦上写具体麦位) 聊天消息
cmd seatChange 频道消息 {[userName, uid, avatar, seat, seatTime]} 麦位更改
cmd picMsg(可方后) 频道消息 imgUrl, imageHeight, imageWidth, avatar, userName, setNum 图片消息
结束语
any自习室项目中还存在一些bug和待完善的功能点。仅供参考,欢迎大家fork。有不足之处欢迎大家指出issues。
最后再贴一下 Github开源下载地址 。
any自习室 Github

    推荐阅读