// // MOWebViewController.m // MiMoLive // // Created by SuperC on 2023/12/25. // // 用于标记webView序号 static int webViewTag = 0; #import "MOWebViewController.h" #import "POWeakWKWebViewScriptMessageHandler.h" #import "MOTopUpVC.h"//充值界面 #import "MOUserHomePageVC.h" // 个人主页 #import "MOUploadDeviceTool.h" @interface MOWebViewController () /** 标记WebView序号 */ @property (nonatomic, assign) int webViewTag; /**记录是否添加了观察者,避免dealloc时释放观察者崩溃*/ @property (nonatomic, assign) BOOL hasAddedObserver; /** 标记是否需要更新钻石 */ @property (nonatomic, assign) BOOL needUpdateDiamond; /** 跳转tag, 防止网页频繁点击跳转 */ @property (nonatomic, assign) BOOL pushTag; @property (strong, nonatomic) UIProgressView *progressView; @property (nonatomic, strong) BigBtn *closeBtn; @end @implementation MOWebViewController - (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; if(self.titleStr.length != 0 || self.isShowTitle){ [self.navigationController setNavigationBarHidden:NO animated:animated]; // [self mo_setNavLeftItemWithImage:[UIImage imageNamed:@"icon_new_left_gray"] andBackgroundImg:[UIImage imageNamed:@"icon_mine_base_bg"]]; [self mo_v2_setNavLeftItemWithImage:[UIImage imageNamed:@"v_2_icon_new_back_black"] andBackgroundImg:nil AndBgColor:nil]; } else{ [self.navigationController setNavigationBarHidden:YES animated:animated]; } if(self.isWame || self.isMiniWame){ [[MOChatNotificationManager sharedManager] enterScene:MOChatNotificationSceneWame];//进入聊天列表场景 } } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self.poWebView loadRequest:self.request]; if(self.isHalfShow){ self.view.backgroundColor = [UIColor clearColor]; [self.poWebView setBackgroundColor:[UIColor clearColor]]; CGFloat topSpacing = SCREENHEIGHT / 2.0 - 100.0; [self.poWebView mas_remakeConstraints:^(MASConstraintMaker *make) { make.left.right.bottom.equalTo(self.view); make.top.equalTo(self.view).offset(topSpacing); }]; } if(self.isWame){ self.isNeedUpdateMoney = YES; self.view.backgroundColor = [UIColor blackColor]; [self.poWebView setBackgroundColor:[UIColor blackColor]]; } //半屏适配 if(self.isMiniWame){ self.isNeedUpdateMoney = YES; CGFloat width = SCREENWIDTH; CGFloat height = width; NSString *urlStr = self.webUrl.absoluteString; if(self.minHeight > 0){ float ratio = (float)750/self.minHeight; height = SCREENWIDTH / ratio; } self.view.backgroundColor = [UIColor clearColor]; [self.poWebView setBackgroundColor:[UIColor whiteColor]]; [self.poWebView mas_remakeConstraints:^(MASConstraintMaker *make) { make.left.right.equalTo(self.view); make.bottom.equalTo(self.view).offset(-12.0); make.height.equalTo(@(height)); }]; } if(self.isRedRain){ self.view.backgroundColor = [UIColor clearColor]; [self.poWebView setBackgroundColor:[UIColor clearColor]]; CGFloat topSpacing = STATUS_BAR_HEIGHT + 70.0; [self.view addSubview:self.closeBtn]; [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.view).offset(topSpacing); make.height.width.equalTo(@30.0); make.right.equalTo(self.view).offset(-15.0); }]; self.closeBtn.layer.cornerRadius = 30.0 / 2.0; self.closeBtn.layer.masksToBounds = YES; } if(self.titleStr.length != 0 ){ self.navigationItem.title = self.titleStr; [self setNavLeftItemWithImage:[UIImage imageNamed:@"icon_nav_back"]]; } if(self.isShowTitle){ [self setNavLeftItemWithImage:[UIImage imageNamed:@"icon_nav_back"]]; } // 添加 KVO 监听器,监听 title 属性的变化 // [self.poWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; // // 创建并添加 UIProgressView // self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; // self.progressView.frame = CGRectMake(0, 300.0, self.view.frame.size.width, 2); // self.progressView.backgroundColor = [UIColor redColor]; // [self.view addSubview:self.progressView]; // // 添加观察者,监听加载进度 // [self.poWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; self.needUpdateDiamond = NO; self.poWebView.allowsBackForwardNavigationGestures = YES; // Set the navigation controller delegate self.navigationController.delegate = self; if (self.blindBoxPaddingTop) { self.view.backgroundColor = [UIColor clearColor]; self.poWebView.opaque = NO; self.poWebView.backgroundColor = [UIColor clearColor]; self.poWebView.scrollView.backgroundColor = [UIColor clearColor]; } } #pragma mark - UINavigationControllerDelegate - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated { if (viewController == self && !self.poWebView.canGoBack) { self.navigationController.interactivePopGestureRecognizer.enabled = YES; } else { self.navigationController.interactivePopGestureRecognizer.enabled = NO; } } - (void)LeftBarItemClick { if(self.isNeedUpdateMoney){ self.needUpdateDiamond = YES; } if (self.isWame) { SendNotification(@"kNotification_CloseWame") } // 左按钮点击触发的事件,实际事件请在在子类重写,可能不是回到上一级视图 NSArray *viewControllers = self.navigationController.viewControllers; if (viewControllers.count > 1) { [self.navigationController popViewControllerAnimated:YES]; } else if (viewControllers.count==1) { [self.navigationController dismissViewControllerAnimated:YES completion:NULL]; } self.closeViewBlock ? self.closeViewBlock() : nil; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if(self.isNeedUpdateMoney){ self.needUpdateDiamond = YES; } if(self.isHalfShow || self.isMiniWame){ if(self.isMiniWame){ WEAKSELF MOTitleNormalAlertView *alertView = [[MOTitleNormalAlertView alloc] init]; alertView.titleLabel.text = NSLocalString(@"mimo_alert_normal_tip"); alertView.subTitleLabel.text = NSLocalString(@"mimo_fan_club_quit_alert_title"); [alertView.cancelBtn setTitle:NSLocalString(@"mimo_Cancel") forState:UIControlStateNormal]; [alertView.confirmBtn setTitle:NSLocalString(@"mimo_TipConfirm") forState:UIControlStateNormal]; alertView.confirmBlock = ^{ //跳转充值界面 (全屏) [weakSelf dismissViewControllerAnimated:YES completion:nil]; }; [alertView show]; } else{ [self dismissViewControllerAnimated:YES completion:nil]; } } else{ [self.navigationController popViewControllerAnimated:YES]; } self.closeViewBlock ? self.closeViewBlock() : nil; } - (void)loadView{ [super loadView]; [self.view addSubview:self.poWebView]; if(self.isHaveSafeTop){ [self.poWebView mas_makeConstraints:^(MASConstraintMaker *make){ make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop); make.left.right.bottom.equalTo(self.view); }]; } else{ [self.poWebView mas_makeConstraints:^(MASConstraintMaker *make){ make.edges.mas_equalTo(0); }]; } if (@available(iOS 11.0,*)) { [self.poWebView.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever]; } else{ self.edgesForExtendedLayout = UIRectEdgeNone; } // [self.poWebView loadRequest:self.request]; } - (WKWebView *)poWebView { if (!_poWebView) { WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; config.selectionGranularity = WKSelectionGranularityDynamic; config.allowsInlineMediaPlayback = YES; config.mediaTypesRequiringUserActionForPlayback = NO; WKPreferences *preferences = [WKPreferences new]; //是否支持JavaScript preferences.javaScriptEnabled = YES; //不通过用户交互,是否可以打开窗口 preferences.javaScriptCanOpenWindowsAutomatically = YES; config.preferences = preferences; [config.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"]; [config setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"]; //新建一个弱引用代理,防止循环引用 POWeakWKWebViewScriptMessageHandler *weakHandler = [[POWeakWKWebViewScriptMessageHandler alloc] initWithSriptMessageHandler:self]; config.userContentController = [self userControllerWithMessageHandler:weakHandler]; _poWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) configuration:config]; [_poWebView setBackgroundColor:[UIColor colorWithRed:242/255. green:242/255. blue:246/255. alpha:1.0]]; [_poWebView setOpaque:NO]; WEAKSELF; [_poWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSString *oldUA = result; NSString *newUA = [NSString stringWithFormat:@"%@/xiaohui",oldUA]; weakSelf.poWebView.customUserAgent = newUA; }]; _poWebView.navigationDelegate = self; _poWebView.UIDelegate = self; [_poWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL]; self.webViewTag = webViewTag; webViewTag++; self.hasAddedObserver = YES; _poWebView.scrollView.bounces = NO;//禁用弹性效果 //FIXME: 默认缓存策略是NSURLRequestUseProtocolCachePolicy #if kAPP_Environment == 1 NSURLRequestCachePolicy policy = NSURLRequestUseProtocolCachePolicy; #elif kAPP_Environment == 2 NSURLRequestCachePolicy policy = NSURLRequestUseProtocolCachePolicy; // NSURLRequestCachePolicy policy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; if (@available(iOS 16.4,*)) { [self.poWebView setInspectable:YES]; } #endif self.request = [NSURLRequest requestWithURL:self.webUrl cachePolicy:policy timeoutInterval:40]; MOLogV(@"[WebView] init poWebView(%d) url:%@",self.webViewTag,self.webUrl); } return _poWebView; } - (WKUserContentController *)userControllerWithMessageHandler:(POWeakWKWebViewScriptMessageHandler *)weakHandler{ WKUserContentController *userController = [[WKUserContentController alloc] init]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_Close]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_GetUserInfo]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_GetStatusHeight]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_GetLanguage]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_GetDiamond]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_ToGetRain]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_ToSubmitShareLink]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_TokenExpired]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_ExportUrl]; // [userController addScriptMessageHandler:weakHandler name:@"recharge"]; [userController addScriptMessageHandler:weakHandler name:@"clickRecharge"]; [userController addScriptMessageHandler:weakHandler name:@"newTppClose"]; // 2 [userController addScriptMessageHandler:weakHandler name:@"getConfig"]; [userController addScriptMessageHandler:weakHandler name:@"destroy"]; [userController addScriptMessageHandler:weakHandler name:[MOTextAESTools toGetHameRecharge]]; [userController addScriptMessageHandler:weakHandler name:[MOTextAESTools toGetHameLoaded]]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_ShareToPlatAgency]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_BindAgencySuccess]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_ChagneMysteriousStatus]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_GetBlindBoxScreenParams]; [userController addScriptMessageHandler:weakHandler name:kWebCallBack_SetBlindBoxResult]; return userController; } - (void)setWameKeyboardHeight:(CGFloat)wameKeyboardHeight{ _wameKeyboardHeight = wameKeyboardHeight; if(wameKeyboardHeight > 100.0){ [self.poWebView mas_updateConstraints:^(MASConstraintMaker *make) { make.bottom.equalTo(self.view).offset(-(wameKeyboardHeight - 100.0)); }]; } else{ [self.poWebView mas_updateConstraints:^(MASConstraintMaker *make) { make.bottom.equalTo(self.view).offset(-12.0); }]; } } #pragma mark ========= JS-->OC =============== - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ //#define kWebCallBack_GetUserInfo @"getUserInfo" //传用户信息 if ([message.name isEqualToString:kWebCallBack_GetUserInfo]) { MOMeDataInfo *userInfoData = (MOMeDataInfo *)[[MODataCache sharedYYCache] objectForKey:kMineUserInfo]; if(userInfoData){ // ADJAttribution *adjInfo = [Adjust attribution]; userInfoData.token = GetToken; userInfoData.adid = [MOUploadDeviceTool shareTool].adid; NSString *versionString = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; userInfoData.appVersion = versionString; NSDictionary *userDict = [userInfoData dictionaryRepresentation]; NSString *jsonString = [userDict modelToJSONString]; NSString *jsString = [NSString stringWithFormat:@"%@(%@)",@"getUserInfoResponse",jsonString]; [self.poWebView evaluateJavaScript:jsString completionHandler:nil]; } else{ NSString *jsonString = @"{\"follows\":3,\"vip\":{\"giveGiftBag\":false,\"type\":0,\"expireTime\":0,\"giveGaily\":false},\"profile\":{\"id\":\"65d4ba9f097a721b1ef0a8c5\",\"intro\":\"\",\"medals\":[],\"userNo\":\"43999352\",\"bks\":[],\"agoraId\":43999352,\"adornment\":{\"headdressAnno\":false,\"bubbleCode\":0,\"enterBar\":0},\"avatar\":\"https:\\/\\/mimo-live.s3.ap-southeast-3.amazonaws.com\\/av\\/2024\\/52\\/b78\\/fa5f8c804caae17d1635afa724149118.jpg\",\"birthday\":\"1990-01-01\",\"nickname\":\"SuperY\",\"country\":\"ID\",\"gender\":1},\"mobile\":{},\"family\":{\"memberMax\":0,\"totalPower\":0,\"level\":0,\"memberNum\":0,\"weekPower\":0,\"dailyPower\":0},\"wallet\":{\"diamond\":22,\"consumeDiamond\":0,\"goldenBean\":0},\"fansClub\":{\"show\":false,\"level\":0,\"rank\":0,\"members\":0},\"currExp\":49,\"guild\":{\"anchor\":0},\"level\":3,\"friends\":1,\"fans\":1,\"nextExp\":113,\"liveBadge\":{\"type\":0},\"status\":{\"anchor\":true,\"guild\":true,\"mobile\":false,\"fansClub\":false,\"liveDiscount\":true,\"anchorType\":1,\"joinFansClub\":true}}"; NSString *jsString = [NSString stringWithFormat:@"%@(%@)",@"getUserInfoResponse",jsonString]; [self.poWebView evaluateJavaScript:jsString completionHandler:nil]; } } //#define kWebCallBack_ToGetRain @"getRedRainInfo" //获取红包雨 else if ([message.name isEqualToString:kWebCallBack_ToGetRain]){ NSDictionary *redRainDict = self.redRainData; NSString *jsonString = [redRainDict modelToJSONString]; NSString *jsString = [NSString stringWithFormat:@"%@(%@)",@"getRedRainInfoResponse",jsonString]; [self.poWebView evaluateJavaScript:jsString completionHandler:nil]; } //#define kWebCallBack_ToSubmitShareLink @"submitShareLink" //分享 else if ([message.name isEqualToString:kWebCallBack_ToSubmitShareLink]){ // 打印出传递的消息内容 MOLogV(@"Received message: %@", message.body); [self shareTheLinkWith:message.body]; } //#define kWebCallBack_TokenExpired @"tokenExpired" //token过期 else if ([message.name isEqualToString:kWebCallBack_TokenExpired]){ [self tokenExpiredAndGetTheUserInfo]; return; } //#define kWebCallBack_ExportUrl @"exportUrl" //导出链接 else if ([message.name isEqualToString:kWebCallBack_ExportUrl]){ [self toExportUrlWith:message.body]; return; } //#define kWebCallBack_Close @"closeActivity" //关闭界面 else if ([message.name isEqualToString:kWebCallBack_Close]){ [self LeftBarItemClick]; if(self.redRainData){ self.needUpdateDiamond = YES; } } //#define kWebCallBack_GetDiamond @"needUpdateDiamond" //获取钻石 else if ([message.name isEqualToString:kWebCallBack_GetDiamond]){ //标记需要更新钻石 self.needUpdateDiamond = YES; } //#define kWebCallBack_GetStatusHeight @"getStatusHeight" //状态栏高度 else if ([message.name isEqualToString:kWebCallBack_GetStatusHeight]){ //顶部高度 CGFloat statusHeght = STATUS_BAR_HEIGHT + 44; //底部高度 CGFloat navigationBarHeight = HOME_KEY_HEIGHT; NSDictionary *userDict = @{@"statusHeight":@(statusHeght),@"navigationBarHeight":@(navigationBarHeight)}; NSString *jsonString = [userDict modelToJSONString]; NSString *jsString = [NSString stringWithFormat:@"%@(%@)",@"getStatusHeightResponse",jsonString]; [self.poWebView evaluateJavaScript:jsString completionHandler:nil]; } //#define kWebCallBack_GetLanguage @"getLanguage" //语言 else if ([message.name isEqualToString:kWebCallBack_GetLanguage]){ NSString *currentLanguage = [NSBundle currentLanguage]; if(currentLanguage.length == 0){ currentLanguage = @"en-us"; } NSDictionary *userDict = @{@"language":currentLanguage}; NSString *jsonString = [userDict modelToJSONString]; NSString *jsString = [NSString stringWithFormat:@"%@(%@)",@"getLanguageResponse",jsonString]; [self.poWebView evaluateJavaScript:jsString completionHandler:nil]; } //MARK: else if ([message.name isEqualToString:@"recharge"]){ if(self.enterBaseData.type == 3){ //so88 [self toPushTopUpVC]; } else{ //百顺 [self noMoneyTipShow]; } } else if ([message.name isEqualToString:@"clickRecharge"]){ [self toPushTopUpVC]; } else if ([message.name isEqualToString:@"newTppClose"]){ [self LeftBarItemClick]; self.needUpdateDiamond = YES; } //MARK: else if ([message.name isEqualToString:@"getConfig"]){ if(self.enterBaseData.type == 3){ [self so88GetConfig:message.body]; } else{ NSDictionary *dicBody = [self dictionaryWithJsonString:message.body]; [self getConfig:dicBody]; } } else if ([message.name isEqualToString:@"destroy"]){ [self LeftBarItemClick]; self.needUpdateDiamond = YES; } else if ([message.name isEqualToString:[MOTextAESTools toGetHameRecharge]]){ [self toPushTopUpVC]; } else if ([message.name isEqualToString:[MOTextAESTools toGetHameLoaded]]){ //加载完毕 MOLogV(@"Loaded finish"); } //全民代理分享 else if ([message.name isEqualToString:kWebCallBack_ShareToPlatAgency]){ // 打印出传递的消息内容 MOLogV(@"Received message: %@", message.body); [self shareTheLinkWith:message.body]; } else if ([message.name isEqualToString:kWebCallBack_BindAgencySuccess]) { SendNotification(@"kNotification_H5BindAgencySuccess") } else if ([message.name isEqualToString:kWebCallBack_ChagneMysteriousStatus]) { [self updateMysteriousSwitchStatus:message.body]; } else if ([message.name isEqualToString:kWebCallBack_GetBlindBoxScreenParams]) { [self setBlindBoxScreenParams]; } else if ([message.name isEqualToString:kWebCallBack_SetBlindBoxResult]) { [self handleBlindBoxGiftResult:message.body]; } } - (void)handleBlindBoxGiftResult:(NSString *)jsonString { NSDictionary *dict = [self dictionaryWithJsonString:jsonString]; MORtmBlindboxDrawResult *result = [MORtmBlindboxDrawResult modelWithJSON:dict]; SendObjNotification(@"kNotification_DrawBlindBoxResut", result) } - (void)setBlindBoxScreenParams { if (!self.blindBoxPaddingTop) { return; } // 屏幕尺寸(pt -> px,乘以 scale) CGFloat scale = [UIScreen mainScreen].scale; if (kBottomSafeAreaInset == 0) { scale = 2; } int width = (int)([UIScreen mainScreen].bounds.size.width * scale); int height = (int)([UIScreen mainScreen].bounds.size.height * scale); int paddingTop = (int)(self.blindBoxPaddingTop.intValue * scale); // 获取当前 roomId NSString *roomId = self.roomId ?: @""; NSString *js = [NSString stringWithFormat:@"setBlindBoxScreenParams(%d,%d,%d,'%@')", width, height, paddingTop, roomId]; [self.poWebView evaluateJavaScript:js completionHandler:^(id _Nullable resp, NSError * _Nullable error) { if (error) { MOLogV(@"调用 H5 setBlindBoxScreenParams 失败: %@", error); } else { MOLogV(@"已通知 H5 调整页面: %@", resp); } }]; } // 刷新神秘人开关本地缓存 - (void)updateMysteriousSwitchStatus:(NSString *)result { NSDictionary *dict = [self dictionaryWithJsonString:result]; NSString *dataResult = [MODataManager objectOrNilForKey:@"data" fromDictionary:dict]; BOOL enable = [dataResult boolValue]; MOMeDataInfo *userInfoData = (MOMeDataInfo *)[[MODataCache sharedYYCache] objectForKey:kMineUserInfo]; userInfoData.userProfile.mysterious = enable; [[MODataCache sharedYYCache] setObject:userInfoData forKey:kMineUserInfo]; [[NSUserDefaults standardUserDefaults] setBool:enable forKey:kIsMysterious]; [[NSUserDefaults standardUserDefaults] synchronize]; } - (void)shareTheLinkWith:(NSString *)jsonString{ // 将 JSON 字符串转化为 NSData NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; // 使用 NSJSONSerialization 将 NSData 转为 NSDictionary NSError *error = nil; NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; if (error) { MOLogV(@"JSON 解析失败: %@", error.localizedDescription); } NSString *methodStr = jsonDict[@"method"]; if([methodStr isEqualToString:kWebCallBack_ToSubmitShareLink]){ NSDictionary *dataDict = jsonDict[@"data"]; NSString *key = dataDict[@"typeStr"]; [self shareURLWith:key]; } else if ([methodStr isEqualToString:kWebCallBack_ShareToPlatAgency]) { NSDictionary *dataDict = jsonDict[@"data"]; [self shareAgency:dataDict]; } } //platName //1. Facebook //2. Instagram //3. Twitter or X //4. Line //5. WhatsApp //6. copy link - (void)shareAgency:(NSDictionary *)dataDict { WEAKSELF int platName = [dataDict[@"platName"] intValue]; NSString *titleStr = dataDict[@"title"]; NSString *contentStr = dataDict[@"content"]; NSString *urlString = dataDict[@"url"]; NSString *imageUrl = dataDict[@"imageUrl"]; #if !TARGET_IPHONE_SIMULATOR SSDKPlatformType playType; SSDKContentType contenType; if (platName == 1) { playType = SSDKPlatformTypeFacebook; contenType = SSDKContentTypeWebPage; imageUrl = nil; } else if (platName == 2) { playType = SSDKPlatformTypeInstagram; contenType = SSDKContentTypeImage; titleStr = nil; } else if (platName == 3) { playType = SSDKPlatformTypeTwitter; contenType = SSDKContentTypeText; contentStr = [NSString stringWithFormat:@"%@ \n %@",contentStr,urlString]; } else if (platName == 4) { playType = SSDKPlatformTypeLine; contenType = SSDKContentTypeText; contentStr = [NSString stringWithFormat:@"%@ \n %@",contentStr,urlString]; } else if (platName == 5) { playType = SSDKPlatformTypeWhatsApp; contenType = SSDKContentTypeText; contentStr = [NSString stringWithFormat:@"%@ \n %@",contentStr,urlString]; } else { //copy UIPasteboard *pab = [UIPasteboard generalPasteboard]; [pab setString:urlString]; if (pab == nil) { [MBProgressHUD showTipMessageInWindow:NSLocalString(@"mimo_money_Failed")]; } else { [MBProgressHUD showTipMessageInWindow:NSLocalString(@"mimo_common_copy_tip")]; } return; } NSMutableDictionary * params = [NSMutableDictionary dictionary]; [params SSDKSetupShareParamsByText:contentStr images:imageUrl url:[NSURL URLWithString:urlString] title:titleStr type:contenType]; [ShareSDK share:playType parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) { switch (state) { case SSDKResponseStateSuccess: MOLogV(@"成功");//成功 [weakSelf toReportAgencyResultResponse:@"1"]; break; case SSDKResponseStateFail: { MOLogV(@"--%@",error.description); if(error.code == 200104){ [MBProgressHUD showTipMessageInWindow:NSLocalString(@"mimo_room_tool_share_no_install_tip")]; } [weakSelf toReportAgencyResultResponse:@"2"]; //失败 break; } case SSDKResponseStateCancel: //取消 [weakSelf toReportAgencyResultResponse:@"3"]; break; default: break; } }]; #endif } - (void)shareURLWith:(NSString *)keyStr{ WEAKSELF NSString *lowerKeyStr = [keyStr lowercaseString]; NSString *titleStr = @"Mimo Live 2025 Hadiah Kesejahteraan Ramadan, login harian untuk menerima hadiah, jutaan diamond diberikan setiap hari!"; NSString *shareStr = [NSString stringWithFormat:@"%@/#/ramadanShareDownload",kNetPath_Web_Base]; NSString *contentStr = [NSString stringWithFormat:@"%@ \n %@",titleStr,shareStr]; //copy UIPasteboard *pab = [UIPasteboard generalPasteboard]; [pab setString:contentStr]; if (pab == nil) { [MBProgressHUD showTipMessageInWindow:NSLocalString(@"mimo_money_Failed")]; } else { [MBProgressHUD showTipMessageInWindow:NSLocalString(@"mimo_common_copy_tip")]; } #if !TARGET_IPHONE_SIMULATOR __block SSDKPlatformType playType; if([lowerKeyStr isEqualToString:@"facebook"]){ playType = SSDKPlatformTypeFacebook; NSMutableDictionary * params = [NSMutableDictionary dictionary]; [params SSDKSetupShareParamsByText:titleStr images:nil url:[NSURL URLWithString:shareStr] title:@"Mimo Live" type:SSDKContentTypeWebPage]; [ShareSDK share:playType parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) { switch (state) { case SSDKResponseStateSuccess: MOLogV(@"成功");//成功 [weakSelf toReportTheShareSuccess]; break; case SSDKResponseStateFail: { MOLogV(@"--%@",error.description); [weakSelf toReportTheShareSuccess]; //失败 break; } case SSDKResponseStateCancel: //取消 [weakSelf toReportTheShareSuccess]; break; default: break; } }]; } else if ([lowerKeyStr isEqualToString:@"instagram"]){ playType = SSDKPlatformTypeInstagram; NSString *mimoImgUrlStr = @"https://s3.mimolive.vip//images/myG9NN-kl69i11nhE795A0zN.png"; NSMutableDictionary * params = [NSMutableDictionary dictionary]; [params SSDKSetupShareParamsByText:contentStr images:@[mimoImgUrlStr] url:[NSURL URLWithString:shareStr] title:nil type:SSDKContentTypeImage]; [ShareSDK share:playType parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) { switch (state) { case SSDKResponseStateSuccess: MOLogV(@"成功");//成功 [weakSelf toReportTheShareSuccess]; break; case SSDKResponseStateFail: { MOLogV(@"--%@",error.description); //失败 [weakSelf toReportTheShareSuccess]; break; } case SSDKResponseStateCancel: //取消 [weakSelf toReportTheShareSuccess]; break; default: break; } }]; } else if ([lowerKeyStr isEqualToString:@"line"]){ playType = SSDKPlatformTypeLine; NSMutableDictionary * params = [NSMutableDictionary dictionary]; [params SSDKSetupShareParamsByText:contentStr images:nil url:nil title:nil type:SSDKContentTypeText]; [ShareSDK share:playType parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) { switch (state) { case SSDKResponseStateSuccess: MOLogV(@"成功");//成功 [weakSelf toReportTheShareSuccess]; break; case SSDKResponseStateFail: { MOLogV(@"--%@",error.description); //失败 [weakSelf toReportTheShareSuccess]; break; } case SSDKResponseStateCancel: //取消 [weakSelf toReportTheShareSuccess]; break; default: break; } }]; } else if ([lowerKeyStr isEqualToString:@"twitter"]){ playType = SSDKPlatformTypeTwitter; NSMutableDictionary * params = [NSMutableDictionary dictionary]; [params SSDKSetupShareParamsByText:contentStr images:nil url:nil title:nil type:SSDKContentTypeText]; [ShareSDK share:playType parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) { switch (state) { case SSDKResponseStateSuccess: MOLogV(@"成功");//成功 [weakSelf toReportTheShareSuccess]; break; case SSDKResponseStateFail: { MOLogV(@"--%@",error.description); //失败 [weakSelf toReportTheShareSuccess]; break; } case SSDKResponseStateCancel: //取消 [weakSelf toReportTheShareSuccess]; break; default: break; } }]; } else if ([lowerKeyStr isEqualToString:@"whatsapp"]){ playType = SSDKPlatformTypeWhatsApp; NSMutableDictionary * params = [NSMutableDictionary dictionary]; [params SSDKSetupShareParamsByText:titleStr images:nil url:[NSURL URLWithString:shareStr] title:@"Mimo Live" type:SSDKContentTypeText]; [ShareSDK share:playType parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) { switch (state) { case SSDKResponseStateSuccess: MOLogV(@"成功");//成功 [weakSelf toReportTheShareSuccess]; break; case SSDKResponseStateFail: { MOLogV(@"--%@",error.description); //失败 [weakSelf toReportTheShareSuccess]; break; } case SSDKResponseStateCancel: //取消 [weakSelf toReportTheShareSuccess]; break; default: break; } }]; } #endif } - (void)toReportTheShareSuccess{ //submitShareLinkResponse() NSString *jsString = [NSString stringWithFormat:@"%@()",kWebCallBack_ToSubmitShareLinkResponse]; [self.poWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable resp, NSError * _Nullable error) { MOLogV(@"error = %@ , response = %@",error, resp); }]; } /// 全民代理分享结果通知H5 /// - Parameter result: 1:成功 2.失败 3.取消 - (void)toReportAgencyResultResponse:(NSString *)result { NSString *jsString = [NSString stringWithFormat:@"%@(%@)",kWebCallBack_GetShareLinkAgencyResultResponse, result]; [self.poWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable resp, NSError * _Nullable error) { MOLogV(@"error = %@ , response = %@",error, resp); }]; } - (void)tokenExpiredAndGetTheUserInfo{ WEAKSELF [kHttpManager getMeUserInfoWithParams:nil andBlock:^(id _Nonnull data, NSError * _Nonnull error) { }]; } - (void)toExportUrlWith:(NSString *)jsonStr{ NSDictionary *dict = [self dictionaryWithJsonString:jsonStr]; NSString *theUrl = [MODataManager objectOrNilForKey:@"url" fromDictionary:dict[@"data"]]; NSURL *url = [NSURL URLWithString:theUrl]; if ([[UIApplication sharedApplication] canOpenURL:url]) { [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil]; } } - (void)getConfig:(NSDictionary *)args{ MOLogV(@"BSWAME %s","调⽤getConfig"); NSString* method = [args objectForKey:@"jsCallback"]; NSString *languagaStr = [MOWebViewController getWameCurrentLanguages]; //gsp 101新加坡 201迪拜 301硅谷 401法兰克福 NSDictionary *configDict = [self.wame2Config dictionaryRepresentation]; NSMutableDictionary *needDict = [NSMutableDictionary dictionaryWithDictionary:configDict]; [needDict setObject:languagaStr forKey:@"language"]; //wameMode 2 半屏 3 全屏 if(self.isMiniWame){ [needDict setObject:@"2" forKey:[MOTextAESTools toGetHameMode]]; } else{ [needDict setObject:@"3" forKey:[MOTextAESTools toGetHameMode]]; } //房间ID NSString *roomId = self.roomId; if(roomId.length == 0){ roomId = @""; } [needDict setObject:roomId forKey:@"roomId"]; [self callJs:method withJavaScriptValue:needDict]; } - (void)so88GetConfig:(NSString *)methodName{ NSString* method = methodName; NSDictionary *configDict = [self.enterBaseData.so88GM dictionaryRepresentation]; NSMutableDictionary *needDict = [NSMutableDictionary dictionaryWithDictionary:configDict]; NSString *languageStr = [self getTheNewCurrentLanguages]; [needDict setObject:languageStr forKey:@"language"]; #if kAPP_Environment == 1 //生产 [needDict setObject:@"4" forKey:@"server"]; #elif kAPP_Environment == 2 //测试 [needDict setObject:@"2" forKey:@"server"]; #endif [self callJs:method withJavaScriptValue:needDict]; } - (void)callJs:(NSString *)method withJavaScriptValue:(nullable id)arguments{ if(arguments){ NSData *data = [NSJSONSerialization dataWithJSONObject:arguments options:(NSJSONWritingPrettyPrinted) error:nil]; NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSString *jsMethods = [NSString stringWithFormat:@"%@(%@)",method,jsonStr]; [self.poWebView evaluateJavaScript:jsMethods completionHandler:^(id _Nullable resp, NSError * _Nullable error) { MOLogV(@"error = %@ , response = %@",error, resp); }]; } else{ NSString *jsMethods = [NSString stringWithFormat:@"%@({})", method]; [self.poWebView evaluateJavaScript:jsMethods completionHandler:^(id _Nullable resp, NSError * _Nullable error) { MOLogV(@"error = %@ , response = %@",error, resp); }]; } } - (void)noMoneyTipShow{ WEAKSELF MOTitleNormalAlertView *alertView = [[MOTitleNormalAlertView alloc] init]; alertView.titleLabel.text = NSLocalString(@"mimo_alert_normal_tip"); alertView.subTitleLabel.text = NSLocalString(@"mimo_no_money_tip"); [alertView.cancelBtn setTitle:NSLocalString(@"mimo_Cancel") forState:UIControlStateNormal]; [alertView.confirmBtn setTitle:NSLocalString(@"mimo_no_money_jump") forState:UIControlStateNormal]; alertView.confirmBlock = ^{ //跳转充值界面 (全屏) [weakSelf toPushTopUpVC]; }; [alertView show]; } - (void)toPushTopUpVC{ if(self.pushTag){ return; } self.pushTag = YES; [self performSelector:@selector(resetPushTag) withObject:nil afterDelay:2.0]; WEAKSELF MOTopUpVC *vc = [[MOTopUpVC alloc] init]; vc.needRefreshBlock = ^{ if(weakSelf.enterBaseData.type == 3){ if(weakSelf.enterBaseData.so88GM.userId.length > 0){ NSObject *map = @{@"userId":weakSelf.enterBaseData.so88GM.userId}; [weakSelf callJs:@"walletUpdate" withJavaScriptValue:map]; } } else{ NSString *userId = GetUserId; if(userId.length > 0){ NSObject *map = @{@"userId":userId}; [weakSelf callJs:@"walletUpdate" withJavaScriptValue:map]; } } }; [self.navigationController pushViewController:vc animated:YES]; } - (void)resetPushTag{ self.pushTag = NO; } - (void)toUserHomePageWithUrl:(NSString *)urlString{ NSString *userId; if ([urlString rangeOfString:@"userId="].location != NSNotFound) { userId = [urlString componentsSeparatedByString:@"userId="].lastObject; } if(userId.length == 0){ return ; } MOUserHomePageVC *vc = [[MOUserHomePageVC alloc] init]; vc.userId = userId; [self.navigationController pushViewController:vc animated:YES]; } - (void)openRechargeView{ NSURL *url = [NSURL URLWithString:@"mimo://jump_native:80/recharge"]; if ([[UIApplication sharedApplication]respondsToSelector:@selector(openURL:options:completionHandler:)]) { [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:^(BOOL success) {}]; } else { [[UIApplication sharedApplication]openURL:url]; } } - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler { } - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // 获取跳转到的新地址 NSString *urlString = webView.URL.absoluteString; MOLogV(@"Navigated to URL: %@", urlString); } /* 开始返回内容 */ - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { NSString *urlString = webView.URL.absoluteString; MOLogV(@"Navigated to URL: %@", urlString); WEAKSELF [webView evaluateJavaScript:@"document.title" completionHandler:^(NSString *title, NSError * _Nullable error) { if(self.isShowTitle){ if(title.length > 0 ){ if([title isEqualToString:@"MINO LIVE"]){ self.navigationItem.title = @"Mimo Live"; } else{ self.navigationItem.title = title; } } } }]; } /* 页面开始加载 */ - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{ NSString *urlString = webView.URL.absoluteString; MOLogV(@"Navigated to URL: %@", urlString); } - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation{ NSString *urlString = webView.URL.absoluteString; MOLogV(@"Navigated to URL: %@", urlString); } - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{ // 在收到响应开始加载后,决定是否跳转 NSString *urlString = webView.URL.absoluteString; MOLogV(@"Navigated to URL: %@", urlString); decisionHandler(WKNavigationResponsePolicyAllow); } /// 页面加载失败,指初始化第一个页面 - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadWebViewData) object:nil]; [self performSelector:@selector(reloadWebViewData) withObject:nil afterDelay:2.0]; } - (void)reloadWebViewData{ #if kAPP_Environment == 1 NSURLRequestCachePolicy policy = NSURLRequestUseProtocolCachePolicy; #elif kAPP_Environment == 2 NSURLRequestCachePolicy policy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; #endif self.request = [NSURLRequest requestWithURL:self.webUrl cachePolicy:policy timeoutInterval:40]; MOLogV(@"[WebView] init poWebView(%d) url:%@",self.webViewTag,self.webUrl); [self.poWebView loadRequest:self.request]; } -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"title"]) { if (object == self.poWebView) { // NSString *newTitle = change[NSKeyValueChangeNewKey]; // MOLogV(@"网页标题变化: %@", newTitle); // self.navigationItem.title = newTitle; } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } // else if ([keyPath isEqualToString:@"estimatedProgress"]) { // self.progressView.progress = self.poWebView.estimatedProgress; // // // 隐藏进度条,当加载完成时 // if (self.poWebView.estimatedProgress >= 1.0) { // self.progressView.hidden = YES; // } else { // self.progressView.hidden = NO; // } // } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } /* 在发送请求之前,决定是否跳转 */ - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{ NSString *urlString = navigationAction.request.URL.absoluteString; MOLogV(@"mimo-urlString-%@",urlString); if([urlString containsString:@"mimo://"]){ NSURL *url = [NSURL URLWithString:urlString]; MOLogV(@"mimo-urlString-%@",urlString); //个人主页跳转 if([urlString containsString:@"mimo://jump_native:80/homePage"]){ [self toUserHomePageWithUrl:urlString]; decisionHandler(WKNavigationActionPolicyCancel); return; } if ([[UIApplication sharedApplication]respondsToSelector:@selector(openURL:options:completionHandler:)]) { [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:^(BOOL success) {}]; } else { [[UIApplication sharedApplication]openURL:webView.URL]; } decisionHandler(WKNavigationActionPolicyCancel); return; } MOLogV(@"12313"); decisionHandler(WKNavigationActionPolicyAllow); } - (void)dealloc{ // [self.poWebView removeObserver:self forKeyPath:@"title"]; [[MOChatNotificationManager sharedManager] leaveScene:MOChatNotificationSceneWame];//进入聊天列表场景 [[MOChatNotificationManager sharedManager] leaveScene:MOChatNotificationSceneWidraw];//进入聊天列表场景 if(self.needUpdateDiamond){ [[MORefreshViewManage shareManager] toUpdataTheUserInfo]; } [self removeHandler]; } - (void)removeHandler{ [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_Close]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_GetUserInfo]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_GetStatusHeight]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_GetLanguage]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_GetDiamond]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_ToGetRain]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_ToSubmitShareLink]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_TokenExpired]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_ExportUrl]; // [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:@"recharge"]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:@"clickRecharge"]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:@"newTppClose"]; // 2 [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:@"getConfig"]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:@"destroy"]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:[MOTextAESTools toGetHameRecharge]]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:[MOTextAESTools toGetHameLoaded]]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_ShareToPlatAgency]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_BindAgencySuccess]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_ChagneMysteriousStatus]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_GetBlindBoxScreenParams]; [_poWebView.configuration.userContentController removeScriptMessageHandlerForName:kWebCallBack_SetBlindBoxResult]; } - (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{ if(jsonString == nil && jsonString.length == 0){ return nil; } NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err]; if(err){ MOLogV(@"json解析失败:%@",err); return nil; } return dic; } - (BigBtn *)closeBtn{ if (!_closeBtn) { _closeBtn = [BigBtn buttonWithType:UIButtonTypeCustom]; _closeBtn.backgroundColor = [MOTools colorWithHexString:@"#000000" alpha:0.3]; [_closeBtn setImage:[UIImage imageNamed:@"icon_live_close"] forState:UIControlStateNormal]; [_closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside]; } return _closeBtn; } - (void)closeBtnClick{ [self LeftBarItemClick]; } + (NSString *)getWameCurrentLanguages{ //2 英语 NSString *defaultLanguageStr = @"2"; NSArray *languages = [NSLocale preferredLanguages]; if(languages.count > 0){ NSString *languageStr = [languages firstObject]; //印尼语 if([languageStr hasPrefix:@"id"]){ defaultLanguageStr = @"3"; } //中文 if([languageStr hasPrefix:@"zh"] || [languageStr hasPrefix:@"tw"]){ defaultLanguageStr = @"0"; } } return defaultLanguageStr; } - (NSString *)getTheNewCurrentLanguages{ NSString *defaultLanguageStr = @"en"; NSArray *languages = [NSLocale preferredLanguages]; if(languages.count > 0){ NSString *languageStr = [languages firstObject]; //中文 if([languageStr hasPrefix:@"zh"] || [languageStr hasPrefix:@"tw"]){ defaultLanguageStr = @"zh"; } } return defaultLanguageStr; } @end