1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491 |
- #import "LiveVideoRoomViewController.h"
- #import "KSChatInputBarControl.h"
- #import "LiveRoomHeadView.h"
- #import "LiveRoomBottomView.h"
- #import "KSRCMessageModel.h"
- #import "UserInfoManager.h"
- #import "KSChatroomMessageCenter.h"
- #import <RongIMKit/RongIMKit.h>
- #import "KSChatroomTextCell.h"
- #import "KSLiveStreamVideo.h"
- #import "SeatContentView.h"
- #import "LiveroomTimeManager.h"
- #import "KSLiveEmptyView.h"
- #import "KSChatVideoView.h"
- #import "LiveRoomLikeLayer.h"
- #import "KSDragWindowManager.h"
- #import "KSLiveBadNetView.h"
- #import <Lottie/Lottie.h>
- #import "KSShopCardView.h"
- #import "KSLiveWebViewController.h"
- #import "KSLiveEndView.h"
- #import "LiveAnimationView.h"
- #import "LiveRoomAlertView.h"
- #import "LiveApplyView.h"
- #import "LiveApplyingView.h"
- #import "ShareLiveDisplayView.h"
- #import "UIImage+KSScreenShot.h"
- #import "TZImageManager.h"
- #import "RecordCheckManager.h"
- #import "KSPremissionAlert.h"
- #import "KSUMShareManager.h"
- #define AUTOHIDE_TIME (10.0f)
- #define PACKAGE_LOST (0.30f)
- typedef NS_ENUM(NSInteger, MICSTATUS) {
- MICSTATUS_NOMAL,
- MICSTATUS_WAITING,
- MICSTATUS_CONNECTING,
- };
- @interface LiveVideoRoomViewController ()<RCRTCEngineEventDelegate,RCRTCRoomEventDelegate,RCRTCStatusReportDelegate,UIGestureRecognizerDelegate,KSChatInputBarControlDelegate,UITableViewDataSource,UITableViewDelegate,LiveroomTimeManagerDelegate>
- @property (nonatomic, strong) LiveroomTimeManager *timeManager;
- @property(strong, nonatomic) RCRTCEngine *engine;
- @property (nonatomic, strong) RCRTCRoom *room;
- @property (nonatomic, strong) KSLiveStreamVideo *localVideo;
- @property (nonatomic) NSMutableArray <KSLiveStreamVideo *>*streamVideos;
- @property (nonatomic, strong) UIView *videoContainerView;
- @property (nonatomic, strong) KSChatVideoView *videoView;
- @property (nonatomic, strong) LiveRoomHeadView *headView;
- @property (nonatomic, copy) LiveRoomBottomView *bottomView;
- @property(nonatomic, assign) NSTimeInterval lastClickPraiseTime;
- @property (nonatomic, assign) MICSTATUS micStatus;
- @property (nonatomic, strong) LiveRoomAlertView *alertView;
- @property (nonatomic, strong) SeatContentView *seatContainer;
- @property(nonatomic, strong) UIView *messageContentView;
- @property (nonatomic, strong) UITableView *conversationMessageTableView;
- @property(nonatomic,strong) KSChatInputBarControl *inputBar;
- @property(nonatomic, assign) BOOL isNeedScrollToButtom;
- @property(nonatomic, strong) NSMutableArray<KSRCMessageModel *> *conversationDataRepository;
- @property (nonatomic, assign) BOOL isImConnected;
- @property (nonatomic, assign) BOOL isCreaterInRoom;
- @property (nonatomic, assign) BOOL isCreaterVideoEnable;
- @property (nonatomic, assign) BOOL isCreaterAudioEnable;
- @property (nonatomic, strong) KSLiveEmptyView *emptyView;
- @property (nonatomic, assign) BOOL isTransferRole;
- @property (nonatomic, assign) BOOL hasSendWelcomeMessage;
- @property (nonatomic, assign) BOOL hasShowSuspendView;
- @property (nonatomic, assign) BOOL isPackageLostTips;
- @property (nonatomic, assign) NSTimeInterval lostStartTime;
- @property (nonatomic, assign) NSTimeInterval bitErrorTime;
- @property (nonatomic, strong) KSLiveBadNetView *netBadView;
- @property (nonatomic, assign) BOOL isLostPackage;
- @property (nonatomic, assign) BOOL isBitError;
- @property (nonatomic, strong) LOTAnimationView *animationView;
- @property (nonatomic, assign) BOOL isCloseRoom;
- @property (nonatomic, strong) KSLiveEndView *endView;
- @property (nonatomic, strong) KSShopCardView *cardView;
- @property (nonatomic, strong) LiveAnimationView *enterAnimationView;
- @property (nonatomic, assign) NSTimeInterval lastSendMsgTime;
- @property (nonatomic, assign) BOOL isOtherLogin;
- @property (nonatomic, strong) LiveApplyView *applyView;
-
- @property (nonatomic, strong) LiveApplyingView *applyingView;
- @property (nonatomic, assign) BOOL isPauseLive;
- @property (nonatomic, strong) ShareLiveDisplayView *shareView;
- @end
- static int clickPraiseBtnTimes = 0;
- @implementation LiveVideoRoomViewController
- - (instancetype)init {
- self = [super init];
- if (self) {
- [self defaultConfig];
- }
- return self;
- }
- - (void)defaultConfig {
- self.enableChat = YES;
- self.enableSeat = YES;
- self.enableLike = YES;
- self.micStatus = MICSTATUS_NOMAL;
- self.isCreaterInRoom = NO;
- self.isImConnected = [USER_MANAGER checkIMConnected];
- self.isCloseRoom = NO;
- self.isOtherLogin = NO;
- }
- - (void)viewDidLoad {
- [super viewDidLoad];
-
- self.ks_prefersNavigationBarHidden = YES;
- [self registerNotification];
- [self setupUI];
- if (self.isImConnected) {
- [self connectService];
- }
- else {
- MJWeakSelf;
- [USER_MANAGER connectionIMCallback:^(BOOL isSuccess) {
- dispatch_main_async_safe(^{
- [weakSelf connectService];
- });
- }];
- }
- [self countUMEvent];
- [self judgeAutoClose];
- }
- - (void)countUMEvent {
- [USER_MANAGER sendUMEvent:@"klx_live"];
- }
- - (void)muteAllAudio {
- if (self.room) {
- [self.room muteAllRemoteAudio:YES];
- }
- }
- - (void)IMConnetedCallback {
- dispatch_main_async_safe(^{
-
- if (self.hasSendWelcomeMessage) {
-
- [KSNetworkingManager liveRoomJoinRoomRequest:KS_GET roomUid:self.roomId success:^(NSDictionary * _Nonnull dic) {
- if ([dic ks_integerValueForKey:@"code"] == 200 && [dic ks_boolValueForKey:@"status"]) {
-
- MJWeakSelf;
- [self notiferJoinSuccessToServiceCallback:^{
- [weakSelf MBPShow:@"IM连接成功"];
- [weakSelf sendWelcomeMessage];
- }];
- }
- else {
- [self MBPShow:MESSAGEKEY];
- [self quitRoom];
- }
- } faliure:^(NSError * _Nonnull error) {
-
- }];
- }
- });
- }
- - (void)sendWelcomeMessage {
- [[RCIMClient sharedRCIMClient] joinExistChatRoom:self.roomId messageCount:-1 success:^{
- KSLiveChatroomWelcome *joinChatroomMessage = [[KSLiveChatroomWelcome alloc] init];
- [joinChatroomMessage setMsgId:[RCIM sharedRCIM].currentUserInfo.userId];
- MJWeakSelf;
- [self sendMessage:joinChatroomMessage displayMessage:NO callback:^(BOOL success) {
- [weakSelf showEnterMessageAndJoinRTCRoom];
- }];
- } error:^(RCErrorCode status) {
- NSLog(@"error code %zd" ,status);
- }];
- }
- - (void)showEnterMessageAndJoinRTCRoom {
-
- NSString *contentString = [NSString stringWithFormat:@"%@ 进入直播间",UserDefault(NicknameKey)];
- [self showAnimationView:YES showMessag:contentString];
- [self joinRTCRoom];
- }
- - (void)leaveRTCRoomCallback:(void(^)(BOOL success))callback {
- [[RCRTCEngine sharedInstance] leaveRoom:^(BOOL isSuccess, RCRTCCode code) {
- callback(isSuccess);
- }];
- }
- - (void)joinRTCRoom {
-
-
- if (self.room && self.liveRoleType == RCRTCLiveRoleTypeBroadcaster) {
- [self connectHostWithStatus:NO];
- }
- else {
- [self setRoleType];
- }
- }
- - (void)judgeAutoClose {
- if (self.isTempRoom == NO) {
- self.timeManager.autoCloseNetworkRoomTime = [self getCloseTime];
- }
- }
- - (void)liveroomLogOut {
- if (self.isOtherLogin) {
- return;
- }
- self.isOtherLogin = YES;
- [self MBPShow:@"该账号在其他设备上登录"];
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self quitRoom];
- [[NSNotificationCenter defaultCenter] postNotificationName:@"liveroomBackRefresh" object:nil];
- });
- }
- - (void)liveroomQuit {
- if (self.isOtherLogin) {
- return;
- }
- self.isOtherLogin = YES;
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self quitRoom];
- [[NSNotificationCenter defaultCenter] postNotificationName:@"liveroomBackRefresh" object:nil];
- });
- }
- - (void)registerNotification {
- [KSChatroomMessageCenter registerMessageTypes];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMessageNotification:) name:OnReceiveChatroomMessageNotification object:nil];
-
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(liveroomLogOut) name:@"liveroomLogout" object:nil];
-
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(liveroomQuit) name:@"liveroomQuit" object:nil];
-
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(IMConnetedCallback) name:@"RongIMConnected" object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(muteAllAudio) name:@"muteLiveAudio" object:nil];
- }
- - (void)setupUI {
- CGSize size = self.view.bounds.size;
- self.view.backgroundColor = HexRGB(0x25292e);
-
- [self.view addSubview:self.emptyView];
- [self.view addSubview:self.endView];
-
-
- [self.view addSubview:self.videoContainerView];
- [self.videoContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.top.bottom.right.mas_equalTo(self.view);
- }];
-
- [self.videoContainerView addSubview:self.videoView];
-
- [self.videoContainerView addSubview:self.netBadView];
- [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.top.bottom.right.mas_equalTo(self.view);
- }];
-
- [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.top.bottom.mas_equalTo(self.videoView);
- }];
- self.emptyView.hidden = YES;
-
- [self.endView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.top.bottom.mas_equalTo(self.videoView);
- }];
- self.endView.hidden = YES;
-
- [self.netBadView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.top.bottom.mas_equalTo(self.videoView);
- }];
- self.netBadView.hidden = YES;
-
- [self.view addSubview:self.headView];
- self.headView.boardcastName.text = [NSString returnNoNullStringWithString:self.createrName];
- if (![NSString isEmptyString:self.createrAvatal]) {
- [self.headView.boardcastAvatal sd_setImageWithURL:[NSURL URLWithString:[self.createrAvatal getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:@"teacher_logo"]];
- }
- [self countLikeMessageCount];
- [self countMemberCount];
- [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.mas_equalTo(self.view);
- make.height.mas_equalTo(80);
- if (@available(iOS 11.0, *)) {
- make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(0);
- } else {
-
- make.top.mas_equalTo(self.view.mas_top).offset(0);
- }
- }];
- [self.view addSubview:self.messageContentView];
-
- if (self.hideCartButton == NO) {
- [self.videoContainerView addSubview:self.animationView];
- [self.animationView mas_makeConstraints:^(MASConstraintMaker *make) {
- if (@available(iOS 11.0, *)) {
- make.bottom.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideBottom).offset(-14);
- } else {
-
- make.bottom.mas_equalTo(self.videoContainerView.mas_bottom).offset(-14);
- }
- make.centerX.mas_equalTo(self.videoContainerView.mas_right).offset(-84);
- make.width.mas_equalTo(48);
- make.height.mas_equalTo(56);
- }];
- [self.animationView play];
- }
- [self.view addSubview:self.bottomView];
- self.bottomView.hideCartVButton = self.hideCartButton;
- [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.mas_equalTo(self.view);
- if (@available(iOS 11.0, *)) {
- make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-10);
- } else {
-
- make.bottom.mas_equalTo(self.view.mas_bottom).offset(-10);
- }
- make.height.mas_equalTo(44);
- }];
-
- [self.messageContentView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.mas_equalTo(self.view.mas_left);
- make.right.mas_equalTo(self.view.mas_right);
- make.bottom.mas_equalTo(self.bottomView.mas_top).offset(-10);
- make.height.mas_equalTo(180);
- }];
- [self.view addSubview:self.inputBar];
- [_inputBar setBackgroundColor: [UIColor whiteColor]];
-
- [_inputBar setFrame:CGRectMake(0, kScreenHeight, size.width , 50)];
- [_inputBar setHidden:YES];
-
- [self.messageContentView addSubview:self.conversationMessageTableView];
- [self.conversationMessageTableView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.top.mas_equalTo(self.messageContentView);
- make.width.mas_equalTo(KPortraitWidth);
- make.bottom.mas_equalTo(self.messageContentView.mas_bottom);
- }];
-
- UITapGestureRecognizer *resetBottomTapGesture =[[UITapGestureRecognizer alloc]
- initWithTarget:self
- action:@selector(resetBottomGesture:)];
- resetBottomTapGesture.delegate = self;
- [self.view addGestureRecognizer:resetBottomTapGesture];
-
- }
- - (void)connectService {
- [self setRoleType];
- [self joinChatRoom];
- }
- - (void)joinChatRoom {
- [[RCIMClient sharedRCIMClient] joinChatRoom:self.roomId messageCount:-1 success:^{
- dispatch_async(dispatch_get_main_queue(), ^{
- [self addConstMessage];
- });
- KSLiveChatroomWelcome *joinChatroomMessage = [[KSLiveChatroomWelcome alloc] init];
- [joinChatroomMessage setMsgId:[RCIM sharedRCIM].currentUserInfo.userId];
- MJWeakSelf;
- [self sendMessage:joinChatroomMessage displayMessage:NO callback:^(BOOL success) {
- weakSelf.hasSendWelcomeMessage = YES;
- NSString *contentString = [NSString stringWithFormat:@"%@ 进入直播间",UserDefault(NicknameKey)];;
- [weakSelf showAnimationView:YES showMessag:contentString];
- }];
-
- } error:^(RCErrorCode status) {
- if (status == RC_CHATROOM_NOT_EXIST || status == KICKED_FROM_CHATROOM || status == RC_PARAMETER_INVALID_CHATROOM) {
- dispatch_async(dispatch_get_main_queue(), ^{
- [self MBPShow:@"加入聊天室失败"];
- });
- }
- }];
- }
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- [UIApplication sharedApplication].idleTimerDisabled = YES;
- [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
- [IQKeyboardManager sharedManager].enable = NO;
- [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
-
- KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
- if (manager.hasShowWindow) {
- [manager resignDragWindow];
- }
- if (self.hasShowSuspendView) {
- KSLiveStreamVideo *mainVideo = nil;
- if (self.videoView.streamId) {
- NSMutableArray *steamArray = [self.streamVideos mutableCopy];
- for (KSLiveStreamVideo *streamVideo in steamArray) {
- if ([streamVideo.streamId isEqualToString:self.videoView.streamId]) {
- mainVideo = streamVideo;
- break;
- }
- }
- }
- if (mainVideo) {
- [self.videoView addSubview:mainVideo.canvesView];
- [mainVideo.canvesView mas_updateConstraints:^(MASConstraintMaker *make) {
- make.left.right.bottom.top.mas_equalTo(self.videoView);
- }];
- }
- _hasShowSuspendView = NO;
- }
- if (self.room) {
- [self.room muteAllRemoteAudio:NO];
- }
- }
- - (void)viewWillDisappear:(BOOL)animated {
- [super viewWillDisappear:animated];
- [UIApplication sharedApplication].idleTimerDisabled = NO;
- [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
- [IQKeyboardManager sharedManager].enable = YES;
- if (@available(iOS 13.0, *)) {
- [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
- } else {
-
- [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
- }
-
-
- if (_timeManager) {
- [_timeManager stopDurationTimer];
- }
- }
- - (void)renderSeatView {
-
- NSMutableArray *seatArray = [NSMutableArray array];
- NSArray *remoteUserArray = [self.room.remoteUsers mutableCopy];
- for (RCRTCRemoteUser *user in remoteUserArray) {
- if (![user.userId isEqualToString:self.videoView.streamUserId] && ![user.userId isEqualToString:self.createrId] && ![user.userId containsString:@"rc_mc_"]) {
- [seatArray addObject:user.userId];
- }
- }
- if (self.micStatus == MICSTATUS_CONNECTING && ![seatArray containsObject:UserDefault(IM_USERID)]) {
- [seatArray addObject:UserDefault(IM_USERID)];
- }
-
- if (seatArray.count) {
- if (![self.videoContainerView.subviews containsObject:self.seatContainer]) {
- [self.videoContainerView addSubview:self.seatContainer];
- }
- [self updateSeatContainerConstraint];
-
- self.seatContainer.seatMemberArray = [NSMutableArray arrayWithArray:seatArray];
- [self.seatContainer refreshSeatUI];
- }
- else {
- [self removeSeatContainer];
- }
- }
- - (void)updateSeatContainerConstraint {
- [self.seatContainer mas_remakeConstraints:^(MASConstraintMaker *make) {
- make.left.right.mas_equalTo(self.videoContainerView);
- make.top.mas_equalTo(self.headView.mas_bottom).offset(0);
- make.height.mas_equalTo(70);
- }];
- }
- - (void)removeSeatContainer {
- if ([self.videoContainerView.subviews containsObject:self.seatContainer]) {
- [self.seatContainer removeFromSuperview];
- }
- }
- - (void)countLikeMessageCount {
- NSInteger count = self.likeCount;
- NSString *desc = @"";
- if (count > 10000) {
- count = count / 10000;
- desc = [NSString stringWithFormat:@"本场点赞%zd万+",count];
- }
- else {
- desc = [NSString stringWithFormat:@"本场点赞%zd",count];
- }
- self.headView.likeCount.text = desc;
- }
- - (void)setRoleType {
- self.micStatus = MICSTATUS_NOMAL;
- [self hideApplyingView];
-
- [self.engine setDefaultAudioRouteToSpeaker:YES];
-
- [self joinLiveRoom];
- }
- - (void)connectHostWithStatus:(BOOL)isConnect {
-
- if (self.isTransferRole) {
- return;
- }
-
- if (isConnect && self.liveRoleType == RCRTCLiveRoleTypeBroadcaster) {
- return;
- }
- else if (isConnect == NO && self.liveRoleType == RCRTCLiveRoleTypeAudience) {
- return;
- }
- self.isTransferRole = YES;
-
- [self removeSeatContainer];
- [self clearVideoViewSource];
- if (isConnect) {
-
- [self.engine.defaultAudioStream setMicrophoneDisable:NO];
- NSArray *streams = @[self.engine.defaultAudioStream];
- MJWeakSelf;
- [self.room.localUser switchToBroadcaster:streams onSucceed:^(RCRTCLiveInfo * _Nonnull liveInfo) {
- weakSelf.isTransferRole = NO;
- dispatch_main_async_safe(^{
- __strong typeof(weakSelf) strongSelf = weakSelf;
-
- strongSelf.liveRoleType = RCRTCLiveRoleTypeBroadcaster;
- NSMutableArray *streamArray = [NSMutableArray array];
- NSArray *remoteUserArray = [strongSelf.room.remoteUsers mutableCopy];
- for (RCRTCRemoteUser *user in remoteUserArray) {
- if (remoteUserArray.count) {
- [streamArray addObjectsFromArray:user.remoteStreams];
- }
- }
- if (streamArray.count) {
- [strongSelf subscribeRemoteResource:streamArray];
- }
- else {
- [strongSelf updateVideoViewContainer];
- }
-
- strongSelf.micStatus = MICSTATUS_CONNECTING;
-
- });
-
- } onFailed:^(RCRTCCode code) {
-
- NSLog(@"------- up error code %ld", code);
- weakSelf.isTransferRole = NO;
- dispatch_main_async_safe(^{
- if (code == RCRTCCodeSwitchRoleSameRoleError) {
- weakSelf.liveRoleType = RCRTCLiveRoleTypeBroadcaster;
-
- weakSelf.micStatus = MICSTATUS_CONNECTING;
-
- [weakSelf renderSeatView];
- }
- else {
-
- [weakSelf MBPShow:@"上麦失败"];
- weakSelf.micStatus = MICSTATUS_NOMAL;
- [weakSelf renderSeatView];
- }
- });
-
- } onKicked:^{
- weakSelf.isTransferRole = NO;
- dispatch_main_async_safe(^{
-
- [weakSelf kickOutLiveRoom];
- });
-
- }];
- }
- else {
- MJWeakSelf;
- [self.room.localUser switchToAudienceOnSucceed:^{
- weakSelf.isTransferRole = NO;
- dispatch_main_async_safe(^{
- __strong typeof(weakSelf) strongSelf = weakSelf;
- strongSelf.liveRoleType = RCRTCLiveRoleTypeAudience;
- [strongSelf.engine.defaultAudioStream setMicrophoneDisable:YES];
-
- NSMutableArray *streamArray = [NSMutableArray array];
- NSArray *remoteUserArray = [strongSelf.room.remoteUsers mutableCopy];
- for (RCRTCRemoteUser *user in remoteUserArray) {
- if (user.remoteStreams.count) {
- [streamArray addObjectsFromArray:user.remoteStreams];
- }
- }
- strongSelf.micStatus = MICSTATUS_NOMAL;
- if (streamArray.count) {
- [strongSelf subscribeRemoteResource:streamArray];
- }
- else {
- [strongSelf updateVideoViewContainer];
- }
-
-
-
-
- [weakSelf sendDownSeatMessage];
- });
-
- } onFailed:^(RCRTCCode code) {
- weakSelf.isTransferRole = NO;
- NSLog(@"------- down error code %ld", code);
- dispatch_main_async_safe(^{
- if (code == RCRTCCodeSwitchRoleSameRoleError) {
- weakSelf.liveRoleType = RCRTCLiveRoleTypeAudience;
- weakSelf.micStatus = MICSTATUS_NOMAL;
- }
- else {
-
- [weakSelf MBPShow:@"下麦失败"];
- weakSelf.micStatus = MICSTATUS_CONNECTING;
- }
-
- [weakSelf renderSeatView];
- });
-
- } onKicked:^{
- weakSelf.isTransferRole = NO;
- dispatch_main_async_safe(^{
-
- [weakSelf kickOutLiveRoom];
- });
- }];
- }
- }
- - (void)kickOutLiveRoom {
- [self MBPShow:@"您已被踢出直播间"];
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self quitRoom];
- });
-
- }
- - (void)countMemberCount {
- NSInteger count = self.totalCount;
- NSString *desc = @"";
- if (count > 10000) {
- count = count / 10000;
- desc = [NSString stringWithFormat:@"%zd万+人",count];
- }
- else {
- desc = [NSString stringWithFormat:@"%zd人",count];
- }
- self.headView.roomMemberCount.text = desc;
- }
- - (void)clearVideoViewSource {
- self.videoView.streamUserId = @"";
- self.videoView.streamTag = @"";
- self.videoView.streamId = @"";
- }
- - (void)clearRemoteContainer {
- [self.streamVideos removeAllObjects];
- [self.videoView removeAllSubViews];
- [self clearVideoViewSource];
- [self removeSeatContainer];
- }
- - (void)updateVideoViewContainer {
- NSMutableArray *steamArray = [self.streamVideos mutableCopy];
- if (steamArray.count > 0) {
-
- KSLiveStreamVideo *mainVideo = nil;
- for (KSLiveStreamVideo *videoSource in steamArray) {
- if ([videoSource.userId isEqualToString:self.createrId]) {
- if ([videoSource.streamTag isEqualToString:@"screenshare"]) {
- if (![self.videoView.streamId isEqualToString:videoSource.streamId]) {
- mainVideo = videoSource;
- }
- break;
- }
- else if ([videoSource.streamTag isEqualToString:@"RongCloudRTC"]) {
- if (![self.videoView.streamId isEqualToString:videoSource.streamId]) {
- mainVideo = videoSource;
- }
- }
- else {
- if (mainVideo == nil) {
- if (![self.videoView.streamId isEqualToString:videoSource.streamId]) {
- mainVideo = videoSource;
- }
- }
- }
- }
- }
-
- if (mainVideo) {
- [self.videoView removeAllSubViews];
- self.videoView.streamUserId = mainVideo.userId;
- self.videoView.streamId = mainVideo.streamId;
- self.videoView.streamTag = mainVideo.streamTag;
- mainVideo.canvesView.tag = 10000;
- [self.videoView addSubview:mainVideo.canvesView];
- [mainVideo.canvesView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.bottom.top.mas_equalTo(self.videoView);
- }];
- }
- }
-
- [self changeEmptyStatusView];
-
- [self renderSeatView];
- }
- - (void)removeViewSubViews:(UIView *)container {
- while (container.subviews.count) {
- [container.subviews.lastObject removeFromSuperview];
- }
- }
- - (void)changeEmptyStatusView {
- if (self.isCreaterInRoom) {
- if (self.isCreaterVideoEnable) {
- self.emptyView.hidden = YES;
- }
- else if (self.isCreaterVideoEnable == NO && self.isCreaterAudioEnable == YES) {
-
- [self showEmptyViewDisplay:YES];
- }
- else {
- [self showEmptyViewDisplay:NO];
- }
- }
- else {
-
- [self.videoView removeAllSubViews];
- [self showEmptyViewDisplay:NO];
- }
- }
- #pragma mark ---- RCRTCRoomEventDelegate
- - (void)didPublishStreams:(NSArray<RCRTCInputStream *> *)streams {
- [self subscribeRemoteResource:streams];
- NSLog(@"didPublishStreams --------");
- }
- - (void)subscribeRemoteResource:(NSArray<RCRTCInputStream *> *)streams {
- [self subscribeRemoteResource:streams isTiny:NO];
- }
- - (void)subscribeRemoteResource:(NSArray<RCRTCInputStream *> *)streams isTiny:(BOOL)isTiny {
-
- NSArray *tinyStream = isTiny ? streams : @[];
- NSArray *ordinaryStream = isTiny ? @[] : streams;
- [self.room.localUser subscribeStream:ordinaryStream
- tinyStreams:tinyStream
- completion:^(BOOL isSuccess, RCRTCCode desc) {
- if (desc != RCRTCCodeSuccess) {
- NSString *errorStr = [NSString stringWithFormat:@"订阅远端流失败:%ld", (long) desc];
- [self MBPShow:errorStr];
- return;
- }
-
-
-
- for (RCRTCInputStream *stream in streams) {
- if ([stream.userId isEqualToString:self.createrId]) {
- self.isPauseLive = NO;
- }
- if (stream.mediaType == RTCMediaTypeVideo) {
- if ([stream.userId isEqualToString:self.createrId]) {
- self.isCreaterVideoEnable = YES;
- [self setupRemoteViewWithStream:stream];
- }
- }
- if (stream.mediaType == RTCMediaTypeAudio && [stream.userId isEqualToString:self.createrId]) {
- self.isCreaterAudioEnable = YES;
- }
- }
-
- [self updateVideoViewContainer];
- }];
- }
- - (KSLiveStreamVideo *)setupRemoteViewWithStream:(RCRTCInputStream *)stream {
-
- KSLiveStreamVideo *sVideo = [self creatStreamVideoWithStreamId:stream.streamId userId:stream.userId tag:stream.tag];
- sVideo.userId = stream.userId;
- RCRTCVideoView *remoteView = (RCRTCVideoView *) sVideo.canvesView;
-
- [(RCRTCVideoInputStream *) stream setVideoView:remoteView];
- return sVideo;
- }
- - (void)didUnpublishStreams:(NSArray<RCRTCInputStream *> *)streams {
- [self unsubscribeRemoteResource:streams orStreamId:nil];
- }
- - (void)stream:(RCRTCInputStream *)stream didVideoEnable:(BOOL)enable {
- NSLog(@"----- video --- staus %d", enable);
- }
- - (void)stream:(RCRTCInputStream *)stream didAudioMute:(BOOL)mute {
- NSLog(@"----- audio --- staus %d", mute);
- if ([stream.userId isEqualToString:self.createrId]) {
- if (mute) {
- self.isCreaterAudioEnable = NO;
- }
- else {
- self.isCreaterAudioEnable = YES;
- }
- [self changeEmptyStatusView];
- }
- }
- - (void)didOfflineUser:(RCRTCRemoteUser *)user {
- [self removeRemoteVideoWithUserId:user.userId];
- [self renderSeatView];
- }
- - (KSLiveStreamVideo *)creatStreamVideoWithStreamId:(NSString *)streamId userId:(NSString *)userId tag:(NSString *)streamTag {
- KSLiveStreamVideo *sVideo = [self fetchStreamVideoWithStreamId:streamId];
- if (!sVideo) {
- sVideo = [[KSLiveStreamVideo alloc] initWithStreamId:streamId streamUserId:userId streamTag:streamTag];
- [self.streamVideos insertObject:sVideo atIndex:0];
- }
- return sVideo;
- }
- - (KSLiveStreamVideo *)fetchStreamVideoWithStreamId:(NSString *)streamId {
- NSMutableArray *streamArray = [self.streamVideos mutableCopy];
- for (KSLiveStreamVideo *sVideo in streamArray) {
- if ([streamId isEqualToString:sVideo.streamId]) {
- return sVideo;
- }
- }
- return nil;
- }
- - (void)fetchStreamVideoOffLineWithStreamId:(NSString *)streamId {
-
- NSArray *arr = [NSArray arrayWithArray:self.streamVideos];
- for (KSLiveStreamVideo *sVideo in arr) {
- if ([streamId isEqualToString:sVideo.streamId]) {
- if (sVideo) {
- [sVideo.canvesView removeFromSuperview];
- [self.streamVideos removeObject:sVideo];
- }
- }
- }
- [self updateVideoViewContainer];
- }
- - (void)didSwitchRoleWithUser:(RCRTCRemoteUser *)user roleType:(RCRTCLiveRoleType)roleType {
- if (roleType == RCRTCLiveRoleTypeAudience) {
- [self renderSeatView];
- }
-
- NSLog(@"didSwitchRoleWithUser --------");
- }
- - (void)judgeRefreshSeatView:(NSString *)userId {
- BOOL needRefresh = NO;
- if (_seatContainer) {
- if (self.seatContainer.seatMemberArray.count && [self.videoContainerView.subviews containsObject:self.seatContainer]) {
- NSMutableArray *memerArray = [self.seatContainer.seatMemberArray mutableCopy];
- for (NSString *memberId in memerArray) {
- if ([userId isEqualToString:memberId]) {
- needRefresh = YES;
- break;
- }
- }
- }
- }
- if (needRefresh) {
- [self renderSeatView];
- }
- }
- - (void)didJoinUser:(RCRTCRemoteUser *)user {
- if ([user.userId isEqualToString:self.createrId]) {
- self.isCreaterInRoom = YES;
-
-
- }
- else {
- }
- NSLog(@"didJoinUser --------");
- }
- - (void)didLeaveUser:(RCRTCRemoteUser *)user {
- [self removeRemoteVideoWithUserId:user.userId];
- if ([user.userId isEqualToString:self.createrId]) {
-
- self.isCreaterInRoom = NO;
- [self resetMicWaitToNomal];
- [self tipsTeacherLeaveRoom];
- [self clearVideoView];
- [self hideTipsView];
- [self showEmptyViewDisplay:NO];
- }
- else {
- [self renderSeatView];
- }
- }
- - (void)removeRemoteVideoWithUserId:(NSString *)userId {
- NSArray *arr = [NSArray arrayWithArray:self.streamVideos];
- for (KSLiveStreamVideo *sVideo in arr) {
- if ([userId isEqualToString:sVideo.userId]) {
- if (sVideo) {
- [sVideo.canvesView removeFromSuperview];
- [self.streamVideos removeObject:sVideo];
- }
- }
- }
- }
- - (void)clearVideoView {
- [self clearVideoViewSource];
- [self.videoView removeAllSubViews];
- }
- - (void)resetConnectionStatus {
- if (self.micStatus == MICSTATUS_CONNECTING) {
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self connectHostWithStatus:NO];
- });
- }
- else {
- [self removeSeatContainer];
- }
- self.micStatus = MICSTATUS_NOMAL;
- }
- - (void)resetMicWaitToNomal {
- if (self.micStatus == MICSTATUS_WAITING) {
- self.micStatus = MICSTATUS_NOMAL;
- }
- }
- - (void)tipsTeacherLeaveRoom {
- [self MBPShow:@"老师已离开房间"];
- }
- #pragma mark - KSChatInputBarControlDelegate
- - (void)onInputBarControlContentSizeChanged:(CGRect)frame withAnimationDuration:(CGFloat)duration andAnimationCurve:(UIViewAnimationCurve)curve {
- CGRect originFrame = _inputBar.frame;
- __weak __typeof(&*self)weakSelf = self;
-
- [UIView animateWithDuration:duration animations:^{
- [UIView setAnimationCurve:curve];
- [weakSelf.inputBar setFrame:CGRectMake(0, frame.origin.y - originFrame.size.height, originFrame.size.width, originFrame.size.height)];
- [UIView commitAnimations];
- }];
- }
- - (void)onTouchSendButton:(NSString *)text {
- if (self.blacklistFlag == YES) {
- [self setDefaultBottomViewStatus];
- return;
- }
- NSDate *date = [NSDate date];
- NSTimeInterval currentInterval = [date timeIntervalSince1970];
- if (currentInterval - self.lastSendMsgTime < 3) {
- [self MBPShow:@"您说话太快啦"];
- return;
- }
-
- if (self.lastSendMsgTime == 0) {
- self.lastSendMsgTime = currentInterval;
- }
-
- if (text.length > 40) {
- [self MBPShow:@"聊天消息需在40个字以内哦"];
- return;
- }
- self.lastSendMsgTime = currentInterval;
- [self touristSendMessage:text];
-
- }
- - (void)touristSendMessage:(NSString *)text {
-
- RCTextMessage *rcTextMessage = [RCTextMessage messageWithContent:text];
- MJWeakSelf;
- [self sendMessage:rcTextMessage displayMessage:YES callback:^(BOOL success) {
- [weakSelf setDefaultBottomViewStatus];
- }];
- }
- #pragma mark ---- RTC
- - (void)joinLiveRoom {
-
- RCRTCRoomConfig *config = [[RCRTCRoomConfig alloc] init];
- config.roomType = RCRTCRoomTypeLive;
- config.liveType = RCRTCLiveTypeAudioVideo;
- config.roleType = RCRTCLiveRoleTypeAudience;
- __weak typeof(self) weakSelf = self;
- [self.engine joinRoom:self.roomId config:config completion:^(RCRTCRoom * _Nullable room, RCRTCCode code) {
- dispatch_main_async_safe(^{
- __strong typeof(weakSelf) strongSelf = weakSelf;
- if (code == RCRTCCodeSignalServerNotConnect || code == RCRTCCodeParameterError || code == RCRTCCodeNotInRTCRoom || code == RCRTCCodeRTCTokenIsNull || code == RCRTCCodeHttpTimeoutError || code == RCRTCCodeHttpError || code == RCRTCCodeVoIPNotAvailable) {
- NSLog(@"%@",[NSString stringWithFormat:@"加入失败 code %ld",code]);
- }
- else {
- [strongSelf notiferJoinSuccessToServiceCallback:^{
-
- }];
- if (room) {
- strongSelf.room = room;
- strongSelf.room.delegate = self;
- }
-
- [strongSelf countMemberCount];
-
-
- if (room.remoteUsers.count) {
- NSMutableArray *streamArray = [NSMutableArray array];
- NSMutableArray *remoteUserArray = [room.remoteUsers mutableCopy];
- for (RCRTCRemoteUser *user in remoteUserArray) {
- if ([user.userId isEqualToString:strongSelf.createrId]) {
- strongSelf.isCreaterInRoom = YES;
- }
- if (user.remoteStreams.count) {
- [streamArray addObjectsFromArray:user.remoteStreams];
- [strongSelf subscribeRemoteResource:streamArray];
- }
- }
- }
- [self changeEmptyStatusView];
- }
- });
- }];
- }
- - (void)closeAlertView {
- if (self.alertView && self.alertView.isShow) {
- [self.alertView removeFromSuperview];
- self.alertView = nil;
- }
- }
- - (void)displayCloseView {
- self.isCloseRoom = YES;
- [self hideTipsView];
-
- [self clearRemoteContainer];
- if (self.micStatus != MICSTATUS_NOMAL) {
- self.micStatus = MICSTATUS_NOMAL;
- self.liveRoleType = RCRTCLiveRoleTypeAudience;
- [self.engine.defaultAudioStream setMicrophoneDisable:YES];
- }
- [self.engine leaveRoom:^(BOOL isSuccess, RCRTCCode code) {
- if (code != RCRTCCodeSuccess) {
-
- }
- }];
- self.endView.hidden = NO;
- [self setDefaultBottomViewStatus];
-
- [[NSNotificationCenter defaultCenter] postNotificationName:@"LiveroomClose" object:nil];
-
- }
- - (void)insertMessage:(RCMessage *)rcMessage userInfo:(NSDictionary *)userInfo {
-
- NSDictionary *leftDic = userInfo;
- if (leftDic && [leftDic[@"left"] isEqual:@(0)]) {
- self.isNeedScrollToButtom = YES;
- }
- [self appendAndDisplayMessage:rcMessage];
- }
- - (void)kickSeatWithMessage:(NSString *)message {
- [self MBPShow:message];
- self.micStatus = MICSTATUS_NOMAL;
- [self connectHostWithStatus:NO];
- }
- - (void)showInviteAlertMessage:(NSString *)tipsMessage {
- if (self.alertView && self.alertView.isShow) {
- [self.alertView removeFromSuperview];
- self.alertView = nil;
- }
- MJWeakSelf;
- self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:tipsMessage leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
- weakSelf.micStatus = MICSTATUS_NOMAL;
- [weakSelf sendSeatResponseMessage:NO];
- } confirm:^{
- [weakSelf sendSeatResponseMessage:YES];
- }];
- }
- - (void)sendSeatResponseMessage:(BOOL)isApprove {
- SEATRESPONSE type = isApprove ? SEATRESPONSE_AUDIENCEAPPROVE : SEATRESPONSE_AUDIENCEREJECT;
- KSLiveChatroomSeatResponse *responseMessage = [[KSLiveChatroomSeatResponse alloc] init];
- responseMessage.type = type;
- responseMessage.audienceId = UserDefault(IM_USERID);
- responseMessage.audienceName = UserDefault(NicknameKey);
- MJWeakSelf;
- [self sendMessage:responseMessage displayMessage:YES callback:^(BOOL success) {
- if (success) {
- if (isApprove) {
- [weakSelf connectHostWithStatus:YES];
- }
- }
- }];
- }
- - (void)showEmptyViewDisplay:(BOOL)isPublish {
- NSString *imageName = @"";
- NSString *descMessage = @"";
- if (isPublish) {
- imageName = @"liveVideo_close";
- descMessage = @"老师已关闭画面!";
- }
- else {
- imageName = @"liveroom_empty";
- descMessage = @"休息一下,马上回来!";
- }
- [self.emptyView configViewWithImageName:imageName desc:descMessage];
- self.emptyView.hidden = NO;
- }
- - (void)exitRoom {
- [self.engine.defaultAudioStream setMicrophoneDisable:YES];
- __weak typeof(self) weakSelf = self;
- [self.engine leaveRoom:^(BOOL isSuccess, RCRTCCode code) {
- dispatch_main_async_safe(^{
- __strong typeof(weakSelf) strongSelf = weakSelf;
- [strongSelf sendLeaveMessageCallback:^(BOOL success) {
-
- [weakSelf quitNotiferService];
- [weakSelf quitChatRoom];
- }];
- });
- }];
- }
- - (void)unsubscribeRemoteResource:(NSArray<RCRTCInputStream *> *)streams orStreamId:(NSString *)streamId {
-
- for (RCRTCInputStream *stream in streams) {
- if (stream.mediaType == RTCMediaTypeVideo) {
- streamId = stream.streamId;
- if ([stream.userId isEqualToString:self.createrId]) {
- [self clearVideoViewSource];
- self.isCreaterVideoEnable = NO;
-
- NSLog(@"----- 停止发布视频流");
- }
- [self fetchStreamVideoOffLineWithStreamId:streamId];
- }
- else if (stream.mediaType == RTCMediaTypeAudio && [stream.userId isEqualToString:self.createrId]) {
-
- NSLog(@"----- 停止发布音频流");
- self.isCreaterAudioEnable = NO;
- }
- }
- }
- #pragma mark -- 加入直播间和退出直播间回到服务
- - (void)notiferJoinSuccessToServiceCallback:(void(^)(void))callback {
- callback();
- [KSNetworkingManager liveRoomJoinRoomRequest:KS_GET roomUid:self.roomId success:^(NSDictionary * _Nonnull dic) {
- callback();
- } faliure:^(NSError * _Nonnull error) {
- callback();
- }];
- }
- #pragma mark -- 退出直播间回掉服务
- - (void)quitNotiferService {
- [KSNetworkingManager LiveroomQuit:KS_POST success:^(NSDictionary * _Nonnull dic) {
- if ([dic ks_integerValueForKey:@"errCode"] == 0) {
- NSLog(@"success");
- }
- else {
- NSLog(@"----- error %@", [dic ks_stringValueForKey:@"errMsg"]);
- }
- } faliure:^(NSError * _Nonnull error) {
-
- }];
- }
- - (void)sendLeaveMessageCallback:(void(^)(BOOL success))callback {
-
- RCUserInfo *currentUserInfo = [RCIM sharedRCIM].currentUserInfo;
- KSLiveChatroomLeave *leaveMessage = [[KSLiveChatroomLeave alloc] init];
- leaveMessage.userId = currentUserInfo.userId;
- leaveMessage.userName = currentUserInfo.name;
- [self sendMessage:leaveMessage displayMessage:NO callback:^(BOOL success) {
- callback(success);
- }];
- }
- - (void)quitChatRoom {
- [[RCIMClient sharedRCIMClient] quitChatRoom:self.roomId success:^{
- NSLog(@"sucess log out--");
- } error:^(RCErrorCode status) {
- NSLog(@"RCErrorCode------%ld ", (long)status);
- }];
- }
- - (void)addConstMessage {
- RCTextMessage *statement = [RCTextMessage messageWithContent:@"欢迎进入直播课堂,请遵守相关法规,禁止传播低俗、暴力等不良信息。为孩子创造健康绿色的学习环境。"];
- statement.extra = @"statement";
- RCMessage *constMessage = [[RCMessage alloc] initWithType:ConversationType_CHATROOM targetId:self.roomId direction:MessageDirection_SEND content:statement];
- constMessage.content.senderUserInfo = [RCIM sharedRCIM].currentUserInfo;
- [self appendAndDisplayMessage:constMessage];
- }
- #pragma mark - views init
- - (void)didReceiveMessageNotification:(NSNotification *)notification {
- NSDictionary *dic = notification.object;
- __block RCMessage *rcMessage = dic[@"message"];
- KSRCMessageModel *model = [[KSRCMessageModel alloc] initWithMessage:rcMessage];
- model.userInfo = rcMessage.content.senderUserInfo;
- if (model.conversationType == ConversationType_CHATROOM && [model.targetId isEqualToString:self.roomId]) {
- __weak typeof(&*self) __blockSelf = self;
- dispatch_main_async_safe((^{
-
- if (rcMessage) {
-
- if ([rcMessage.content isMemberOfClass:[KSLiveChatroomLike class]]) {
- return;
- }
- else if ([rcMessage.content isMemberOfClass:[RCChatroomLikeCount class]]) {
- RCChatroomLikeCount *likeCountMessage = (RCChatroomLikeCount *)rcMessage.content;
- __blockSelf.likeCount = likeCountMessage.count;
- [__blockSelf countLikeMessageCount];
- return;
- }
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomWelcome class]]) {
-
- if ([rcMessage.senderUserId isEqualToString:UserDefault(IM_USERID)]) {
- return;
- }
-
- RCUserInfo *userInfo = rcMessage.content.senderUserInfo;
- NSString *userName = [userInfo.name stringByAppendingString:@""];
- NSString *contentMsg = [NSString stringWithFormat:@"%@ 进入直播间",userName];
- [__blockSelf showAnimationView:YES showMessag:contentMsg];
- }
-
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomLeave class]]) {
- return;
- }
-
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomUserQuit class]]) {
- return;
- }
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomKickOut class]]) {
- KSLiveChatroomKickOut *kickMessage = (KSLiveChatroomKickOut *)rcMessage.content;
- NSString *currentUserId = UserDefault(IM_USERID);
- if ([kickMessage.targetId isEqualToString:currentUserId]) {
- __blockSelf.micStatus = MICSTATUS_NOMAL;
- [__blockSelf kickOutLiveRoom];
- }
- return;
- }
-
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomMemberUp class]]) {
- KSLiveChatroomMemberUp *member = (KSLiveChatroomMemberUp *)rcMessage.content;
- __blockSelf.totalCount = member.count;
- [__blockSelf countMemberCount];
- return;
- }
-
- else if ([rcMessage.content isMemberOfClass:[RCChatroomSeatsControl class]]) {
- RCChatroomSeatsControl *seatControlMessage = (RCChatroomSeatsControl *)rcMessage.content;
- if (seatControlMessage.seatBan) {
- __blockSelf.enableSeat = NO;
-
-
- if (__blockSelf.micStatus != MICSTATUS_CONNECTING) {
- __blockSelf.micStatus = MICSTATUS_NOMAL;
- }
-
- [__blockSelf hideApplyView];
- [__blockSelf hideApplyingView];
- }
- else {
- __blockSelf.enableSeat = YES;
- }
- [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
- }
-
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomSeatApply class]]) {
- KSLiveChatroomSeatApply *seatApplyMessage = (KSLiveChatroomSeatApply *)rcMessage.content;
-
- if (![seatApplyMessage.audienceId isEqualToString:UserDefault(IM_USERID)]) {
-
- return;
- }
- if (seatApplyMessage.type == SEATHANDLE_INVITE) {
- NSString *titles = [NSString stringWithFormat:@"%@邀请您连麦",[NSString returnNoNullStringWithString:seatApplyMessage.teacherName]];
- [__blockSelf showInviteAlertMessage:titles];
- }
- else if (seatApplyMessage.type == SEATHANDLE_DISINVITE) {
- [__blockSelf MBPShow:@"老师撤回了连麦邀请"];
- if (__blockSelf.alertView && __blockSelf.alertView.isShow) {
- [__blockSelf.alertView dismissAlertView];
- }
- }
- else if (seatApplyMessage.type == SEATHANDLE_KICKSEAT) {
- [__blockSelf kickSeatWithMessage:@"您已被抱下麦"];
- }
- [__blockSelf hideApplyingView];
- [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
- }
-
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomSeatResponse class]]) {
- KSLiveChatroomSeatResponse *seatResponseMessage = (KSLiveChatroomSeatResponse *)rcMessage.content;
- if (![seatResponseMessage.audienceId isEqualToString:UserDefault(IM_USERID)]) {
- return;
- }
- if (seatResponseMessage.type == SEATRESPONSE_TEACHERAPPROVE && __blockSelf.micStatus == MICSTATUS_WAITING) {
- [__blockSelf hideApplyingView];
- [__blockSelf connectHostWithStatus:YES];
- [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
- }
- else if (seatResponseMessage.type == SEATRESPONSE_TEACHERREJECT) {
- [__blockSelf MBPShow:@"老师拒绝了您的连麦申请"];
- __blockSelf.micStatus = MICSTATUS_NOMAL;
- [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
- }
- }
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomDownSeat class]]) {
- return;
- }
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomDownSeat class]]) {
-
- return;
- }
- else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomClose class]]) {
- [__blockSelf MBPShow:@"直播已结束"];
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
-
- [__blockSelf closeAlertView];
- [__blockSelf displayCloseView];
- [__blockSelf hideApplyingView];
- });
- return;
- }
- else if ([rcMessage.content isMemberOfClass:[RCTextMessage class]]) {
- [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
- }
- else if ([rcMessage.content isMemberOfClass:[KSRCPauseLiveMessage class]]) {
- __blockSelf.isPauseLive = YES;
- [__blockSelf MBPShow:@"老师已暂停直播"];
- if (__blockSelf.micStatus == MICSTATUS_WAITING) {
- [__blockSelf sendSeatMessageApply:NO];
- }
- [__blockSelf resetConnectionStatus];
- [__blockSelf resetNetTips];
- [__blockSelf closeAlertView];
- [__blockSelf hideApplyingView];
- return;
- }
- else if ([rcMessage.content isMemberOfClass:[KSRCShopRushMessage class]]) {
-
- KSRCShopRushMessage *rushMsg = (KSRCShopRushMessage *)rcMessage.content;
-
- NSString *contentMsg = [NSString stringWithFormat:@"%@ 正在抢购",[NSString returnNoNullStringWithString:rushMsg.userName]];
- [__blockSelf showAnimationView:NO showMessag:contentMsg];
- }
- else if ([rcMessage.content isMemberOfClass:[KSLiveBlockUser class]]) {
- KSLiveBlockUser *blockMessage = (KSLiveBlockUser *)rcMessage.content;
- if ([blockMessage.userId isEqualToString:UserDefault(IM_USERID)]) {
- __blockSelf.blacklistFlag = YES;
- [__blockSelf resetConnectionStatus];
- }
- }
- else if ([rcMessage.content isMemberOfClass:[KSLiveUnBlockUser class]]) {
- KSLiveUnBlockUser *unBlockMessage = (KSLiveUnBlockUser *)rcMessage.content;
- if ([unBlockMessage.userId isEqualToString:UserDefault(IM_USERID)]) {
- __blockSelf.blacklistFlag = NO;
- }
- }
- else if ([rcMessage.content isMemberOfClass:[KSDownSeatAllMessage class]]) {
- if (__blockSelf.micStatus == MICSTATUS_CONNECTING) {
- [__blockSelf kickSeatWithMessage:@"您已被抱下麦"];
- [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
- }
- }
- else if ([rcMessage.content isMemberOfClass:[KSRejectAllSeatMessage class]]) {
- if (__blockSelf.micStatus == MICSTATUS_WAITING) {
- [__blockSelf MBPShow:@"老师拒绝了您的连麦申请"];
-
- __blockSelf.micStatus = MICSTATUS_NOMAL;
- [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
- [__blockSelf hideApplyingView];
- }
- }
- }
- }));
- }
- }
- - (void)hideApplyView {
- if (self.applyView.isShow) {
- [self.applyView hideView];
- }
- }
- - (void)hideApplyingView {
- if (self.applyingView.isShow) {
- [self.applyingView hideView];
- }
- }
- - (void)sendMemberCountMessage {
- KSLiveChatroomMemberCount *syncMessage = [[KSLiveChatroomMemberCount alloc] init];
- syncMessage.count = self.totalCount;
-
- [self sendMessage:syncMessage displayMessage:NO callback:^(BOOL success) {
-
- }];
- }
- #pragma mark ----- time manager delegate
- - (void)quitClassroomNotifer {
- [self MBPShow:@"直播课已结束!"];
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self quitAction];
- });
- }
- #pragma mark - gesture and button action
- - (void)resetBottomGesture:(UIGestureRecognizer *)gestureRecognizer {
- if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
- [self setDefaultBottomViewStatus];
- }
- }
- - (void)setDefaultBottomViewStatus {
- [self.inputBar setInputBarStatus:KSBottomBarStatusDefault];
- [self.inputBar setHidden:YES];
- }
- #pragma mark ---- sendMessage/showMessage
- - (void)sendMessage:(RCMessageContent *)messageContent displayMessage:(BOOL)displayMessage callback:(void(^)(BOOL success))callback {
- if (_roomId == nil) {
- return;
- }
- messageContent.senderUserInfo = [RCIM sharedRCIM].currentUserInfo;
- if (messageContent == nil) {
- return;
- }
- __weak typeof(&*self) __weakself = self;
- [KSChatroomMessageCenter sendChatMessage:self.roomId content:messageContent success:^(long messageId) {
- dispatch_async(dispatch_get_main_queue(), ^{
- RCMessage *message = [[RCMessage alloc] initWithType:ConversationType_CHATROOM targetId:__weakself.roomId direction:MessageDirection_SEND content:messageContent];
- message.content.senderUserInfo = [RCIM sharedRCIM].currentUserInfo;
-
- message.senderUserId = UserDefault(IM_USERID);
- if (displayMessage) {
- [__weakself appendAndDisplayMessage:message];
- }
- [__weakself.inputBar clearInputView];
- callback(YES);
- });
-
- } error:^(RCErrorCode errorCode, long messageId) {
- if (errorCode == RC_CHATROOM_NOT_EXIST) {
- dispatch_async(dispatch_get_main_queue(), ^{
- [__weakself MBPShow:@"聊天已被解散,请退出后重进。"];
- });
- }
- dispatch_async(dispatch_get_main_queue(), ^{
- [__weakself.inputBar clearInputView];
- NSLog(@"发送失败,errorcode is: %ld",(long)errorCode);
- callback(NO);
- });
- }];
- }
- - (void)appendAndDisplayMessage:(RCMessage *)rcMessage {
- if (!rcMessage) {
- return;
- }
-
- KSRCMessageModel *model = [[KSRCMessageModel alloc] initWithMessage:rcMessage];
- model.userInfo = rcMessage.content.senderUserInfo;
- if (!model.userInfo) {
- model.userInfo = [RCIMClient sharedRCIMClient].currentUserInfo;
- }
-
- if ([self appendMessageModel:model]) {
- NSIndexPath *indexPath =
- [NSIndexPath indexPathForItem:self.conversationDataRepository.count - 1
- inSection:0];
- if ([self.conversationMessageTableView numberOfRowsInSection:0] !=
- self.conversationDataRepository.count - 1) {
- return;
- }
-
- [self.conversationMessageTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
- if ([self isAtTheBottomOfTableView] || self.isNeedScrollToButtom) {
- [self scrollToBottomAnimated:YES];
- self.isNeedScrollToButtom=NO;
- }
- }
- return;
- }
- - (BOOL)appendMessageModel:(KSRCMessageModel *)model {
-
- if (!model.content) {
- return NO;
- }
-
-
-
-
- if (self.conversationDataRepository.count>500) {
-
- KSRCMessageModel *message = self.conversationDataRepository[0];
- [[RCIMClient sharedRCIMClient]deleteMessages:@[@(message.messageId)]];
- [self.conversationDataRepository removeObjectAtIndex:0];
- [self.conversationMessageTableView reloadData];
- }
-
- [self.conversationDataRepository addObject:model];
- return YES;
- }
- - (BOOL)isAtTheBottomOfTableView {
- if (self.conversationMessageTableView.contentSize.height <= self.conversationMessageTableView.frame.size.height) {
- return YES;
- }
- if(self.conversationMessageTableView.contentOffset.y +200 >= (self.conversationMessageTableView.contentSize.height - self.conversationMessageTableView.frame.size.height)) {
- return YES;
- }else{
- return NO;
- }
- }
- - (void)scrollToBottomAnimated:(BOOL)animated {
- if ([self.conversationMessageTableView numberOfSections] == 0) {
- return;
- }
- NSUInteger finalRow = MAX(0, [self.conversationMessageTableView numberOfRowsInSection:0] - 1);
- if (0 == finalRow) {
- return;
- }
- NSIndexPath *finalIndexPath =
- [NSIndexPath indexPathForItem:finalRow inSection:0];
- [self.conversationMessageTableView scrollToRowAtIndexPath:finalIndexPath atScrollPosition:UITableViewScrollPositionTop animated:animated];
- }
- #pragma mark ----- table data source
- - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
- return self.conversationDataRepository.count;
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
- KSRCMessageModel *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
- RCMessageContent *messageContent = model.content;
- KSChatroomTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KSChatroomTextCell"];
- if(!cell){
- cell = [[KSChatroomTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"KSChatroomTextCell"];
- }
- if ([messageContent isMemberOfClass:[RCTextMessage class]] || [messageContent isMemberOfClass:[KSLiveChatroomWelcome class]] || [messageContent isMemberOfClass:[KSLiveChatroomLike class]] || [messageContent isMemberOfClass:[KSLiveChatroomSeatApply class]] || [messageContent isMemberOfClass:[KSLiveChatroomSeatResponse class]] || [messageContent isMemberOfClass:[KSDownSeatAllMessage class]] || [messageContent isMemberOfClass:[KSRejectAllSeatMessage class]] || [messageContent isMemberOfClass:[RCChatroomSeatsControl class]]){
- [cell setDataModel:model createrId:self.createrId];
- }
- return cell;
- }
- - (void)sendSeatMessageApply:(BOOL)isApply {
- if (self.micStatus == MICSTATUS_CONNECTING) {
- [self MBPShow:@"您已上麦"];
- return;
- }
- SEATHANDLE type = isApply ? SEATHANDLE_APPLY : SEATHANDLE_CANCELAPPLY;
- KSLiveChatroomSeatApply *applyMessage = [[KSLiveChatroomSeatApply alloc] init];
- applyMessage.type = type;
- applyMessage.audienceId = UserDefault(IM_USERID);
- applyMessage.audienceName = UserDefault(NicknameKey);
- applyMessage.audienceAvatar = UserDefault(AvatarUrlKey);
- applyMessage.teacherId = self.createrId;
- applyMessage.teacherName = self.createrName;
- MJWeakSelf;
- [self sendMessage:applyMessage displayMessage:YES callback:^(BOOL success) {
- if (success) {
- weakSelf.micStatus = isApply ? MICSTATUS_WAITING : MICSTATUS_NOMAL;
- }
- }];
- }
- - (void)praiseBtnPressed {
- NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
- __weak __typeof(&*self)weakSelf = self;
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.21 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- if ([[NSDate date] timeIntervalSince1970] - self.lastClickPraiseTime >= 0.2) {
-
- KSLiveChatroomLike *praiseSendMessage = [[KSLiveChatroomLike alloc] init];
- praiseSendMessage.counts = clickPraiseBtnTimes;
- [weakSelf sendMessage:praiseSendMessage displayMessage:NO callback:^(BOOL success) {
-
- }];
- clickPraiseBtnTimes = 0;
-
- }
- });
- KSLiveChatroomLike *praiseMessage = [[KSLiveChatroomLike alloc] init];
- clickPraiseBtnTimes++;
- self.lastClickPraiseTime = currentTime;
- [self presentLikeMessageAnimation:praiseMessage];
-
- }
- - (void)presentLikeMessageAnimation:(KSLiveChatroomLike *)likeMessage {
- LiveRoomLikeLayer *layer = [[LiveRoomLikeLayer alloc] initWithName:@"Like"];
- [self.view.layer addSublayer:layer];
- CGRect tempFrame = [self.view convertRect:self.bottomView.likeButton.frame fromView:self.bottomView];
- CGFloat width = tempFrame.size.width;
- CGFloat height = tempFrame.size.height;
- CGFloat dx = CGRectGetMidX(tempFrame) - width *0.5;
- CGFloat dy = CGRectGetMidY(tempFrame) - 8 - height;
- layer.frame = CGRectMake(dx, dy, width, height);
- [layer startAnimation];
- }
- #pragma mark - setter & getter
- - (void)setMicStatus:(MICSTATUS)micStatus {
- _micStatus = micStatus;
- if (self.bottomView) {
- switch (micStatus) {
- case MICSTATUS_NOMAL:
- {
- [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seat_nomal"] forState:UIControlStateNormal];
- }
- break;
- case MICSTATUS_WAITING:
- {
- [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seating_image"] forState:UIControlStateNormal];
- }
- break;
- case MICSTATUS_CONNECTING:
- {
- [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seat_image"] forState:UIControlStateNormal];
- }
- break;
- default:
- break;
- }
- }
- }
- #pragma mark ----- RCRTCEngineEventDelegate
- - (void)didRTCConnectionStateChanged:(RCRTCConnectionState)state {
- if (state == RCRTCConnectionStateConnecting) {
- NSLog(@"--------RCRTCConnectionStateConnecting");
- }
- else if (state == RCRTCConnectionStateConnected) {
- NSLog(@"--------RCRTCConnectionStateConnected");
- }
- }
- #pragma mark ----- RCRTCStatusReportDelegate
- - (void)didReportStatusForm:(RCRTCStatusForm *)form {
-
-
- for (RCRTCStreamStat *stat in form.recvStats) {
-
- if ([stat.mediaType isEqualToString:@"video"]) {
- if (stat.packetLoss >= PACKAGE_LOST) {
- if (self.lostStartTime == 0) {
- self.lostStartTime = [[NSDate date] timeIntervalSince1970];
- }
- else {
- NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
- if (currentTime - self.lostStartTime >= 8) {
- self.isLostPackage = YES;
- [self showBadNetTips];
- }
- }
- }
- else {
- self.lostStartTime = 0;
- self.isLostPackage = NO;
- [self hideTipsView];
- }
-
- if (stat.bitRate == 0) {
- if (self.bitErrorTime == 0) {
- self.bitErrorTime = [[NSDate date] timeIntervalSince1970];
- }
- else {
- NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
- if (currentTime - self.bitErrorTime >= 5) {
- self.isBitError = YES;
- [self showBadNetTips];
- }
- }
- }
- else {
- self.isBitError = NO;
- self.bitErrorTime = 0;
- [self hideTipsView];
- }
- }
- }
- }
- - (void)showBadNetTips {
- dispatch_main_async_safe(^{
- if (self.isCloseRoom == NO) {
- if (self.netBadView.hidden == YES) {
- self.netBadView.hidden = NO;
- self.videoView.hidden = YES;
- }
- }
- });
- }
- - (void)hideTipsView {
- dispatch_main_async_safe(^{
- if (self.netBadView.hidden == NO) {
- if (self.isBitError == NO && self.isLostPackage == NO) {
- self.netBadView.hidden = YES;
- self.videoView.hidden = NO;
- }
- }
-
- })
-
- }
- #pragma mark --- lazying
- - (KSChatVideoView *)videoView {
- if (!_videoView) {
- _videoView = [[KSChatVideoView alloc] initWithFrame:self.view.bounds];
- _videoView.backgroundColor = [UIColor clearColor];
- }
- return _videoView;
- }
- - (UIView *)videoContainerView {
- if (!_videoContainerView) {
- _videoContainerView = [[UIView alloc] initWithFrame:CGRectZero];
- _videoContainerView.backgroundColor = [UIColor clearColor];
- }
- return _videoContainerView;
- }
- - (LiveRoomHeadView *)headView {
- if (!_headView) {
- _headView = [LiveRoomHeadView shareInstance];
- MJWeakSelf;
- [_headView quitAction:^{
- [weakSelf showQuitAlert];
- }];
- }
- return _headView;
- }
- - (void)showTeacherCenter {
-
- }
- - (void)showQuitAlert {
- if (self.isCloseRoom) {
- [self quitRoom];
- }
- else if (self.micStatus == MICSTATUS_CONNECTING) {
- [self quitAction];
- }
- else {
- MJWeakSelf;
- self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:@"是否退出直播间" leftButtonTitle:@"取消" rightTitle:@"退出" inView:self.view cancel:^{
-
- } confirm:^{
- [weakSelf quitAction];
- }];
- }
- }
- - (LiveRoomBottomView *)bottomView {
- if (!_bottomView) {
- _bottomView = [LiveRoomBottomView shareInstance];
- MJWeakSelf;
- [_bottomView bottomClickAction:^(LIVEROOMACTION action) {
- [weakSelf bottomViewAction:action];
- }];
- }
- return _bottomView;
- }
- - (void)bottomViewAction:(LIVEROOMACTION)action {
- if (self.isCloseRoom) {
- [self MBPShow:@"直播已结束"];
- return;
- }
- switch (action) {
- case LIVEROOMACTION_CHAT:
- {
- if (self.blacklistFlag == YES) {
- [self MBPShow:@"您已被老师禁言"];
- return;
- }
-
- [_inputBar setHidden:NO];
- [_inputBar setInputBarStatus:KSBottomBarStatusKeyboard];
-
- }
- break;
- case LIVEROOMACTION_SEAT:
- {
-
- if (self.micStatus == MICSTATUS_CONNECTING) {
-
- MJWeakSelf;
- self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:@"连麦中,确认取消连麦吗?" leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
-
- } confirm:^{
- [weakSelf connectHostWithStatus:NO];
- }];
-
- }
- else if (self.micStatus == MICSTATUS_WAITING) {
-
- [self displayApplyingView];
- }
- else {
- if (self.blacklistFlag == YES) {
- [self MBPShow:@"您已被老师禁言"];
- return;
- }
- if (self.isCreaterInRoom == NO) {
- [self MBPShow:@"老师不在直播间"];
- return;
- }
- if (self.isPauseLive == YES) {
- [self MBPShow:@"老师暂停中,暂时无法接受邀请"];
- return;
- }
- if (self.enableSeat) {
-
- [self displaySeatApplyView];
- }
- else {
- [self MBPShow:@"老师关闭连麦申请"];
- }
- }
- }
- break;
- case LIVEROOMACTION_SHOP:
- {
- [self showCartAlert];
- }
- break;
- case LIVEROOMACTION_LIKE:
- {
- if (self.isCreaterInRoom) {
- [self praiseBtnPressed];
- }
- else {
- [self MBPShow:@"老师不在直播间"];
- }
- }
- break;
- default:
- break;
- }
- }
- - (void)showShareAlert {
- NSString *qrUrl = [NSString stringWithFormat:@"%@%@?id=%@&userId=%@",WEBHOST,@"/#/shareLiveRoom",self.roomId,UserDefault(UIDKey)];
- self.shareView = [ShareLiveDisplayView shareInstance];
- [self.shareView configWithTeacherAvatar:self.createrAvatal teacherName:self.createrName qrUrl:qrUrl];
- MJWeakSelf;
- [self.shareView shareActionCallback:^(SHARETYPE type) {
- UIImage *image = [UIImage getCurrentViewShot:weakSelf.shareView.containerView];
- if (type == SHARETYPE_SAVE) {
- [weakSelf savePicWithImage:image];
- }
- else {
- [weakSelf showShareUI:image];
- }
- }];
- [self.shareView showShareViewInView:self.view];
- }
- - (void)displaySeatApplyView {
- [self.applyView showInView:self.view];
- }
- - (void)displayApplyingView {
- [self.applyingView showInView:self.view];
- }
- - (void)showCartAlert {
- [self.cardView showViewInView:self.view];
- }
- - (void)quitAction {
- if (self.micStatus == MICSTATUS_CONNECTING) {
- MJWeakSelf;
- self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:@"连麦中,是否退出房间?" leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
-
- } confirm:^{
- [weakSelf quitRoom];
- }];
- }
- else {
- [self quitRoom];
- }
-
- }
- - (void)quitRoom {
- KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
- if (manager.hasShowWindow) {
- [manager resignDragWindow];
- }
-
- [self clearRemoteContainer];
-
- [self exitRoom];
- [self.navigationController dismissViewControllerAnimated:YES completion:nil];
- }
- - (RCRTCEngine *)engine {
- if (!_engine) {
- _engine = [RCRTCEngine sharedInstance];
- [_engine setStatusReportDelegate:self];
- [_engine setDelegate:self];
- }
- return _engine;
- }
- - (NSMutableArray<KSLiveStreamVideo *> *)streamVideos {
- if (!_streamVideos) {
- _streamVideos = [NSMutableArray array];
- }
- return _streamVideos;
- }
- - (KSLiveStreamVideo *)localVideo {
- if (!_localVideo) {
- _localVideo = [KSLiveStreamVideo LocalStreamVideo];
- }
- return _localVideo;
- }
- - (UIView *)messageContentView {
- if (!_messageContentView) {
- _messageContentView = [[UIView alloc] init];
- [_messageContentView setBackgroundColor: [UIColor clearColor]];
- }
- return _messageContentView;
- }
- - (NSMutableArray<KSRCMessageModel *> *)conversationDataRepository {
- if (!_conversationDataRepository) {
- _conversationDataRepository = [NSMutableArray array];
- }
- return _conversationDataRepository;
- }
- - (KSChatInputBarControl *)inputBar {
- if (!_inputBar) {
- _inputBar = [[KSChatInputBarControl alloc] initWithStatus:KSBottomBarStatusDefault];
- [_inputBar setDelegate:self];
- }
- return _inputBar;
- }
- - (UITableView *)conversationMessageTableView {
- if (!_conversationMessageTableView) {
- _conversationMessageTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
- _conversationMessageTableView.backgroundColor = [UIColor clearColor];
- _conversationMessageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
- _conversationMessageTableView.dataSource = self;
- _conversationMessageTableView.delegate = self;
- _conversationMessageTableView.rowHeight = UITableViewAutomaticDimension;
- _conversationMessageTableView.estimatedRowHeight = 40.0f;
- _conversationMessageTableView.showsVerticalScrollIndicator = NO;
- [_conversationMessageTableView registerClass:[KSChatroomTextCell class] forCellReuseIdentifier:@"KSChatroomTextCell"];
- }
- return _conversationMessageTableView;
- }
- - (SeatContentView *)seatContainer {
- if (!_seatContainer) {
- _seatContainer = [[SeatContentView alloc] init];
- }
- return _seatContainer;
- }
- - (KSLiveEmptyView *)emptyView {
- if (!_emptyView) {
- _emptyView = [[KSLiveEmptyView alloc] init];
- _emptyView.backgroundColor = [UIColor clearColor];
- BOOL isPhoneLive = YES;
- [_emptyView dispPlayViewIsPhoneLive:isPhoneLive];
- }
- return _emptyView;
- }
- - (KSLiveEndView *)endView {
- if (!_endView) {
- _endView = [[KSLiveEndView alloc] init];
- _endView.backgroundColor = HexRGB(0x25292e);
- BOOL isPhoneLive = YES;
- [_endView dispPlayViewIsPhoneLive:isPhoneLive];
- }
- return _endView;
- }
- - (KSLiveBadNetView *)netBadView {
- if (!_netBadView) {
- _netBadView = [[KSLiveBadNetView alloc] init];
- BOOL isPhoneLive = YES;
- [_netBadView dispPlayViewIsPhoneLive:isPhoneLive];
- MJWeakSelf;
- [_netBadView configViewWithImageName:@"liveVideo_close" desc:@"当前网络状态不佳" callback:^{
- [weakSelf resetAllConnection];
- }];
- }
- return _netBadView;
- }
- - (LOTAnimationView *)animationView {
- if (!_animationView) {
- _animationView = [LOTAnimationView animationWithFilePath:[[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"LiveCard" ofType:@"bundle"]] pathForResource:@"cardAnimation" ofType:@"json"]];
- _animationView.loopAnimation = YES;
- }
- return _animationView;
- }
- - (void)resetNetTips {
- self.lostStartTime = 0;
- self.isBitError = NO;
- self.bitErrorTime = 0;
- self.isLostPackage = NO;
- [self hideTipsView];
- }
- - (void)setBlacklistFlag:(BOOL)blacklistFlag {
- _blacklistFlag = blacklistFlag;
- [self refreshBottomChatStatus];
- }
- - (void)refreshBottomChatStatus {
- if (self.bottomView) {
- NSString *tipsTitle = self.blacklistFlag ? @"您已被老师禁言" : @"快来互动吧!";
- self.bottomView.tipsLabel.text = tipsTitle;
- }
- }
- - (void)resetAllConnection {
- [self resetNetTips];
-
- [self.streamVideos removeAllObjects];
- [self clearVideoViewSource];
- [self removeSeatContainer];
-
-
-
-
- [self.engine.defaultAudioStream setMicrophoneDisable:YES];
- __weak typeof(self) weakSelf = self;
-
- [self.engine leaveRoom:^(BOOL isSuccess, RCRTCCode code) {
- __strong typeof(weakSelf) strongSelf = weakSelf;
- if (code != RCRTCCodeSuccess) {
-
- }
-
- [strongSelf joinLiveRoom];
- }];
-
- }
- - (void)sendDownSeatMessage {
- KSLiveChatroomDownSeat *downSeatMessage = [[KSLiveChatroomDownSeat alloc] init];
- downSeatMessage.audienceId = UserDefault(IM_USERID);
- downSeatMessage.audienceName = UserDefault(NicknameKey);
- MJWeakSelf;
- [self sendMessage:downSeatMessage displayMessage:NO callback:^(BOOL success) {
- weakSelf.micStatus = MICSTATUS_NOMAL;
- }];
- }
- - (LiveroomTimeManager *)timeManager {
- if (!_timeManager) {
- _timeManager = [[LiveroomTimeManager alloc] initWithDelegate:self];
- }
- return _timeManager;
- }
- - (NSInteger)getCloseTime {
- NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
- [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
- formatter.timeZone = [NSTimeZone systemTimeZone];
- NSDate *currentDate = [NSDate date];
- NSDate *expireDate = [formatter dateFromString:self.liveEndTime];
- NSTimeInterval timeInterval = [expireDate timeIntervalSinceDate:currentDate];
- return self.expiredMinute * 60 + timeInterval;
- }
- - (KSShopCardView *)cardView {
- if (!_cardView) {
- _cardView = [KSShopCardView shareInstance];
- MJWeakSelf;
- [_cardView clickAction:^(CART_TYPE type) {
- [weakSelf displayTeacherInfo:type];
- }];
- }
- return _cardView;
- }
- - (void)displayTeacherInfo:(CART_TYPE)type {
- [self sendRushMessage];
- RCRTCVideoView *videoView = nil;
- for (UIView *view in self.videoView.subviews) {
- if ([view isKindOfClass:[RCRTCVideoView class]]) {
- videoView = (RCRTCVideoView *)view;
- }
- }
- if (videoView) {
- _hasShowSuspendView = YES;
- KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
- [manager initDragWindowWithPhoneLive:YES];
- manager.rootVC = (CustomNavViewController *)self.navigationController;
-
- [videoView removeFromSuperview];
- [manager.dragWindow.containerView addSubview:videoView];
- [videoView mas_updateConstraints:^(MASConstraintMaker *make) {
- make.left.right.top.bottom.mas_equalTo(manager.dragWindow.containerView);
- }];
- [manager.dragWindow bringSubviewToFront:manager.dragWindow.cancelButton];
- }
-
- NSString *tabs = @"";
- switch (type) {
- case CART_TYPE_NONE:
- {
- tabs = @"";
- }
- break;
- case CART_TYPE_ACCOMPANY:
- {
- tabs = @"practice";
- }
- break;
- case CART_TYPE_LIVE:
- {
- tabs = @"live";
- }
- break;
- case CART_TYPE_VIDEO:
- {
- tabs = @"video";
- }
- break;
- case CART_TYPE_MUSIC:
- {
- tabs = @"music";
- }
- break;
- default:
- break;
- }
- NSString *url = @"";
- if ([NSString isEmptyString:tabs]) {
- url = [NSString stringWithFormat:@"%@%@%@", WEBHOST,@"/#/teacherHome?teacherId=",self.createrId];
- }
- else {
- url = [NSString stringWithFormat:@"%@%@%@&tabs=%@", WEBHOST,@"/#/teacherHome?teacherId=",self.createrId,tabs];
- }
- KSLiveWebViewController *ctrl = [[KSLiveWebViewController alloc] init];
- ctrl.url = url;
- [self.navigationController pushViewController:ctrl animated:YES];
- }
- - (void)sendRushMessage {
- }
- - (void)showAnimationView:(BOOL)isJoinRoom showMessag:(NSString *)message {
- if (self.enterAnimationView && self.enterAnimationView.isShow) {
- return;
- }
- else {
- ANIMATIONTYPE type = isJoinRoom ? ANIMATIONTYPE_JOIN : ANIMATIONTYPE_RUSH;
- self.enterAnimationView = [[LiveAnimationView alloc] initWithTitle:message animationType:type];
- [self.view addSubview:self.enterAnimationView];
- [self.enterAnimationView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.mas_equalTo(self.view);
- make.width.mas_equalTo(KPortraitWidth);
- make.height.mas_equalTo(24.0f);
- make.bottom.mas_equalTo(self.messageContentView.mas_top).offset(-6);
- }];
- [self.view bringSubviewToFront:self.enterAnimationView];
-
- MJWeakSelf;
- [self.enterAnimationView startAnimationEndCallback:^{
-
- weakSelf.enterAnimationView.isShow = NO;
- weakSelf.enterAnimationView = nil;
- }];
- }
- }
- - (void)dealloc {
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
- - (LiveApplyView *)applyView {
- if (!_applyView) {
- _applyView = [LiveApplyView shareInstance];
- MJWeakSelf;
- [_applyView applySeatCallback:^{
- [weakSelf applySeatAction];
- }];
- }
- return _applyView;
- }
- - (void)applySeatAction {
- [self MBPShow:@"已发起连麦申请"];
- [self sendSeatMessageApply:YES];
- }
- - (LiveApplyingView *)applyingView {
- if (!_applyingView) {
- _applyingView = [LiveApplyingView shareInstance];
- NSString *avatar = UserDefaultObjectForKey(AvatarUrlKey);
- [_applyingView.myAvatal sd_setImageWithURL:[NSURL URLWithString:[avatar getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:USERDEFAULT_LOGO]];
- [_applyingView.teacherAvatal sd_setImageWithURL:[NSURL URLWithString:[self.createrAvatal getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:USERDEFAULT_LOGO]];
- MJWeakSelf;
- [_applyingView cancleApplyCallback:^{
- [weakSelf cancleApplyAction];
- }];
- }
- return _applyingView;
- }
- - (void)cancleApplyAction {
- MJWeakSelf;
- self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:@"连麦申请中,确认取消连麦申请吗?" leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
-
- } confirm:^{
- [weakSelf.applyingView hideView];
- [weakSelf sendSeatMessageApply:NO];
- }];
- }
- - (void)showShareUI:(UIImage *)image {
- [KSUMShareManager shareInstanceWithImage:image url:@"" shareTitle:@"" descMessage:@"" shareType:KSSHARETYPE_IMAGE showInView:self callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
- if (isSuccess) {
- [self.shareView hideView];
- }
- else {
- }
- [self MBPShow:descMessage];
- }];
- }
- - (void)savePicWithImage:(UIImage *)image {
-
- PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable:NO showInView:nil];
- if (albumEnable == PREMISSIONTYPE_YES) {
-
- [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) {
- if (!error) {
- [self .shareView hideView];
- [self MBPShow:@"保存成功"];
- }
- else {
- [self MBPShow:@"保存图片失败"];
- }
- }];
- }
- else {
- if (albumEnable == PREMISSIONTYPE_NO) {
- [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
- }
- }
- }
- - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
- [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
-
- } confirm:^{
- [self openSettingView];
- }];
-
- }
- - (void)openSettingView {
- if (@available(iOS 10, *)) {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
- } else {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
- }
- }
- @end
|