1. 程式人生 > 其它 >IOS技術分享| any自習室場景實現

IOS技術分享| any自習室場景實現

前言

線上自習室,又稱“線上自習室”“雲自習室”“雲上自習室”“雲端自習室”,是一種用網際網路技術打造的線上自習室。線上自習室打破了時間、空間的束縛,比線下自習室更便捷,形式更多樣。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))
        }
    }

自習室信令參照表

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