写点什么

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

发布于: 1 小时前

前言

线上自习室,又称“在线自习室”“云自习室”“云上自习室”“云端自习室”,是一种用互联网技术打造的在线自习室。线上自习室打破了时间、空间的束缚,比线下自习室更便捷,形式更多样。anyRTC 作为全球实时音视频云服务供应商,推出了 any 自习室,致力于帮助开发者更快地实现实时互动场景。

场景实现

效果截屏

iOS 体验 & 源码下载

开发环境

  • 开发工具: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
复制代码

示例代码

效果展示
代码实现
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 = 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 = 0 var 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 = value                let attributeOptions = ARtmChannelAttributeOptions()        attributeOptions.enableNotificationToChannelMembers = true                rtmEngine.addOrUpdateChannel(infoVideoModel.roomId!, attributes: [channelAttribute], options: attributeOptions) { (errorCode) in            print("addOrUpdateChannel code: \(errorCode.rawValue)")        }    }
复制代码

成员列表

效果展示
代码实现
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() }}
复制代码

发送图片消息

效果展示
实现代码

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.0                let 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: - ARtmChannelDelegate        func channel(_ channel: ARtmChannel, messageReceived message: ARtmMessage, from member: ARtmMember) {        //收到频道消息回调        let dic = getDictionaryFromJSONString(jsonString: message.text)        let value: String? = dic.object(forKey: "cmd") as? String                if value == "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))        }    }
复制代码

自习室信令参照表

结束语

any 自习室项目中还存在一些 bug 和待完善的功能点。仅供参考,欢迎大家 fork。有不足之处欢迎大家指出 issues。最后再贴一下 Github 开源下载地址 。


any自习室 Github

发布于: 1 小时前阅读数: 2
用户头像

实时交互,万物互联! 2020.08.10 加入

实时交互,万物互联,全球实时互动云服务商领跑者!

评论

发布
暂无评论
IOS技术分享| any自习室场景实现