KSBaseWKWebViewController.m 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. //
  2. // KSBaseWKWebViewController.m
  3. // KulexiuForTeacher
  4. //
  5. // Created by Kyle on 2022/3/17.
  6. //
  7. #import "KSBaseWKWebViewController.h"
  8. #import "JPUSHService.h"
  9. #import "LoginViewController.h"
  10. #import "AppDelegate.h"
  11. #import "CustomNavViewController.h"
  12. #import <RongIMKit/RongIMKit.h>
  13. #import "UIDevice+TFDevice.h"
  14. #import "KSPremissionAlert.h"
  15. #import "RecordCheckManager.h"
  16. #import "KSLocalWebViewController.h"
  17. #import "RCConnectionManager.h"
  18. #import "KSAccompanyWebViewController.h"
  19. #import "KSChatConversationViewController.h"
  20. #import "KSOrderManager.h"
  21. #import "AddressListViewController.h"
  22. #import "KSEnterLiveroomManager.h"
  23. @interface KSBaseWKWebViewController ()
  24. @property (nonatomic, assign) BOOL isOutLink; // 外部链接
  25. @property (nonatomic,weak) CALayer *progressLayer;
  26. @property (nonatomic, strong) NSString *currerntURL; // 当前web URL
  27. @property (nonatomic, assign) BOOL hasModify;
  28. @property (nonatomic, assign) BOOL hasChangeSource; // 是否切换了亮屏,横屏等配置
  29. @property (nonatomic, assign) BOOL landScape;
  30. @end
  31. @implementation KSBaseWKWebViewController
  32. - (void)viewDidLoad {
  33. [super viewDidLoad];
  34. // Do any additional setup after loading the view.
  35. self.ks_prefersNavigationBarHidden = YES; // 隐藏导航栏,其他事件额外处理
  36. [self initWebView];
  37. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(operationDealCallbackMessage:) name:DEALCALLBACKNOTICIFATION object:nil];
  38. }
  39. - (void)operationDealCallbackMessage:(NSNotification *)notification {
  40. NSString *status = [notification object];
  41. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  42. [sendParm setValue:@"paymentOperation" forKey:@"api"];
  43. [sendParm setValue:status forKey:@"status"];
  44. [self postMessage:sendParm];
  45. }
  46. - (void)setParmDic:(NSDictionary *)parmDic {
  47. _parmDic = parmDic;
  48. _hasChangeSource = YES;
  49. BOOL isOpenLight = [parmDic boolValueForKey:@"isOpenLight"];
  50. [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
  51. // 横竖屏
  52. NSInteger orientation = [parmDic integerValueForKey:@"orientation"];
  53. BOOL isLandScape = orientation == 0 ? YES : NO;
  54. if (_landScape != isLandScape) {
  55. [self changeOrientation:isLandScape];
  56. }
  57. // 是否隐藏头部导航条
  58. self.hideTop = [parmDic boolValueForKey:@"isHideTitle"];
  59. }
  60. - (void)changeOrientation:(BOOL)isLandScape {
  61. self.landScape = isLandScape;
  62. if (isLandScape) {
  63. // 切换到横屏
  64. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  65. delegate.allowAutoRotate = YES;
  66. [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
  67. }
  68. else {
  69. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  70. delegate.allowAutoRotate = NO;
  71. [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
  72. }
  73. }
  74. - (void)viewWillAppear:(BOOL)animated {
  75. [super viewWillAppear:animated];
  76. if (_hasChangeSource) {
  77. [self setParmDic:self.parmDic];
  78. }
  79. }
  80. - (void)viewWillDisappear:(BOOL)animated {
  81. [super viewWillDisappear:animated];
  82. if (_hasChangeSource && self.keepOrientation == NO && self.landScape == YES) {
  83. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  84. [self changeOrientation:NO];
  85. }
  86. self.keepOrientation = NO;
  87. }
  88. - (void)initWebView {
  89. [self.view addSubview:self.navView];
  90. CGFloat topHeight = kNaviBarHeight;
  91. if (self.hideTop) {
  92. topHeight = 0.0f;
  93. }
  94. [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
  95. make.left.right.top.mas_equalTo(self.view);
  96. make.height.mas_equalTo(topHeight);
  97. }];
  98. [self.view addSubview:self.webBackButton];
  99. [self.webBackButton mas_makeConstraints:^(MASConstraintMaker *make) {
  100. make.left.top.mas_equalTo(self.view);
  101. make.height.mas_equalTo(kNaviBarHeight);
  102. make.width.mas_equalTo(44);
  103. }];
  104. if (self.hideTop) {
  105. self.webBackButton.hidden = YES;
  106. }
  107. if (_hiddenNavBar) {
  108. topHeight = 0.0f;
  109. }
  110. if (self.headTitle) {
  111. [self.navView.topTitleLabel setText:_headTitle];
  112. }
  113. if (_myWebView == nil) {
  114. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  115. config.selectionGranularity = WKSelectionGranularityDynamic;
  116. config.allowsInlineMediaPlayback = YES;
  117. if (@available(iOS 10.0, *)) {
  118. config.mediaTypesRequiringUserActionForPlayback = NO;
  119. } else {
  120. // Fallback on earlier versions
  121. config.requiresUserActionForMediaPlayback = NO;
  122. }
  123. config.processPool = [KSBaseWKWebViewController singleWkProcessPool];
  124. config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  125. //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
  126. WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
  127. //这个类主要用来做native与JavaScript的交互管理
  128. WKUserContentController * wkUController = [[WKUserContentController alloc] init];
  129. [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"COLEXIU"];
  130. config.userContentController = wkUController;
  131. WKPreferences *preferences = [WKPreferences new];
  132. // 是否支出javaScript
  133. preferences.javaScriptEnabled = YES;
  134. //不通过用户交互,是否可以打开窗口
  135. preferences.javaScriptCanOpenWindowsAutomatically = YES;
  136. config.preferences = preferences;
  137. _myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
  138. _myWebView.UIDelegate = self;
  139. _myWebView.navigationDelegate = self;
  140. _myWebView.scrollView.bounces = NO;
  141. _myWebView.scrollView.showsVerticalScrollIndicator = NO;
  142. _myWebView.scrollView.showsHorizontalScrollIndicator = NO;
  143. // 加载进度条和title
  144. [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  145. [_myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
  146. [self.view addSubview:_myWebView];
  147. [_myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
  148. make.left.right.mas_equalTo(self.view);
  149. make.top.mas_equalTo(self.view.mas_top).offset(topHeight);
  150. make.bottom.mas_equalTo(self.view.mas_bottom).offset(-iPhoneXSafeBottomMargin);
  151. }];
  152. if (@available(iOS 11.0, *)) {
  153. _myWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  154. } else {
  155. // Fallback on earlier versions
  156. }
  157. [self setupProgress];
  158. // 修改userAgent
  159. [self setUserAgent];
  160. [self.view bringSubviewToFront:self.navView];
  161. [self.view bringSubviewToFront:self.webBackButton];
  162. }
  163. else {
  164. [_myWebView reload];
  165. }
  166. }
  167. - (void)setUserAgent {
  168. MJWeakSelf;
  169. [self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
  170. NSString *oldUserAgent = result;
  171. NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@",oldUserAgent,@"COLEXIUAPPI"];
  172. weakSelf.myWebView.customUserAgent = newUserAgent;
  173. [weakSelf loadRequest];;
  174. }];
  175. }
  176. - (void)loadRequest {
  177. MJWeakSelf;
  178. [self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
  179. NSLog(@"%@",result);
  180. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:weakSelf.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  181. [weakSelf.myWebView loadRequest:request];
  182. }];
  183. }
  184. - (NSString *)url {
  185. if (_url) {
  186. // if ([_url containsString:hostURL]) {
  187. if ([_url containsString:@"Authorization="]) {
  188. NSRange range = [_url rangeOfString:@"Authorization="];
  189. if (range.location != NSNotFound) {
  190. _url = [_url substringToIndex:range.location-1];
  191. }
  192. }
  193. NSString *sepectString = [_url containsString:@"?"] ? @"&" : @"?";
  194. NSString *tokenStr = UserDefault(TokenKey);
  195. if (![NSString isEmptyString:tokenStr]) {
  196. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  197. _url = [NSString stringWithFormat:@"%@%@%@",_url, sepectString, token];
  198. }
  199. // }
  200. }
  201. return _url;
  202. }
  203. #pragma mark --- 返回按钮的处理
  204. - (void)backAction {
  205. [self.myWebView stopLoading];
  206. if (_backRootView) {
  207. [self.navigationController popToRootViewControllerAnimated:NO];
  208. return;
  209. }
  210. else if (_isBackPreView) {
  211. [self.navigationController popViewControllerAnimated:YES];
  212. return;
  213. }
  214. else if ([self.myWebView canGoBack]) {
  215. [self.myWebView goBack];
  216. }
  217. else {
  218. [self.navigationController popViewControllerAnimated:YES];
  219. }
  220. }
  221. #pragma mark - WKScriptMessageHandler
  222. - (void)userContentController:(WKUserContentController *)userContentController
  223. didReceiveScriptMessage:(WKScriptMessage *)message {
  224. if ([message.name isEqualToString:@"COLEXIU"]) {
  225. NSDictionary *parm = [self convertJsonStringToNSDictionary:message.body];
  226. // 回到主线程
  227. dispatch_async(dispatch_get_main_queue(), ^{
  228. [self handleScriptMessageSource:parm];
  229. });
  230. }
  231. }
  232. - (void)handleScriptMessageSource:(NSDictionary *)parm {
  233. if ([[parm stringValueForKey:@"api"] isEqualToString:@"back"]) { // 返回
  234. [self.navigationController popViewControllerAnimated:YES];
  235. }
  236. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"login"]) {
  237. // 回到登录页面
  238. [self backLoginView];
  239. }
  240. // chat
  241. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openConversationActivity"]) {
  242. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  243. NSString *name = [valueDic stringValueForKey:@"name"];
  244. NSString *userId = [NSString stringWithFormat:@"%.0f",[valueDic floatValueForKey:@"userId"]];
  245. KSChatConversationViewController *conversationVC = [[KSChatConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:[NSString returnNoNullStringWithString:userId]];
  246. conversationVC.title = [NSString returnNoNullStringWithString:name];
  247. [self.navigationController pushViewController:conversationVC animated:YES];
  248. }
  249. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openWebView"]) { // 打开新页面
  250. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  251. KSBaseWKWebViewController *detailCtrl = [[KSBaseWKWebViewController alloc] init];
  252. detailCtrl.url = [valueDic stringValueForKey:@"url"];
  253. detailCtrl.parmDic = valueDic;
  254. NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
  255. BOOL isLandScape = orientation == 0 ? YES : NO;
  256. if (isLandScape == self.landScape) {
  257. self.keepOrientation = YES;
  258. detailCtrl.keepOrientation = YES;
  259. }
  260. [self postMessage:parm];
  261. [self.navigationController pushViewController:detailCtrl animated:YES];
  262. }
  263. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"setRequestedOrientation"]) {
  264. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  265. // 横竖屏
  266. NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
  267. BOOL isLandScape = orientation == 0 ? YES : NO;
  268. [self changeOrientation:isLandScape];
  269. }
  270. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"keepScreenLongLight"]) {
  271. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  272. BOOL isOpenLight = [valueDic boolValueForKey:@"isOpenLight"];
  273. [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
  274. }
  275. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"downLoad"]) {
  276. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  277. if ([valueDic stringValueForKey:@"PDF"]) {
  278. NSString *url = [valueDic stringValueForKey:@"downloadUrl"];
  279. [KSNetworkingManager downloadFileRequestWithFileUrl:url progress:^(int64_t bytesRead, int64_t totalBytes) {
  280. } success:^(NSURL * _Nonnull fileUrl) {
  281. MJWeakSelf;
  282. [self KSShowMsg:@"下载成功" promptCompletion:^{
  283. [weakSelf displaySource:fileUrl];
  284. }];
  285. } faliure:^(NSError * _Nonnull error) {
  286. }];
  287. }
  288. }
  289. // 回调是否刘海屏
  290. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"isSpecialShapedScreen"]) {
  291. BOOL isShapedScreen = iPhoneXSafeTopMargin > 0 ? YES : NO;
  292. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm dictionaryValueForKey:@"content"]];
  293. [valueDic setValue:@(isShapedScreen) forKey:@"isSpecialShapedScreen"];
  294. [valueDic setValue:@(iPhoneXSafeTopMargin*2) forKey:@"notchHeight"];
  295. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  296. [sendParm setValue:valueDic forKey:@"content"];
  297. [self postMessage:sendParm];
  298. }
  299. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"getToken"]) {
  300. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm dictionaryValueForKey:@"content"]];
  301. [valueDic setValue:UserDefault(Token_type) forKey:@"tokenType"];
  302. [valueDic setValue:UserDefault(TokenKey) forKey:@"accessToken"];
  303. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  304. [sendParm setValue:valueDic forKey:@"content"];
  305. [self postMessage:sendParm];
  306. }
  307. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openAccompanyWebView"]) { // 打开伴奏
  308. PREMISSIONTYPE micEnable = [RecordCheckManager checkPermissionShowAlert:NO showInView:nil];
  309. PREMISSIONTYPE cameraEnable = [RecordCheckManager checkCameraPremissionAvaiable:NO showInView:nil];
  310. if (micEnable == PREMISSIONTYPE_YES && cameraEnable == PREMISSIONTYPE_YES) { // 如果麦克风和摄像头权限都有
  311. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  312. KSAccompanyWebViewController *detailCtrl = [[KSAccompanyWebViewController alloc] init];
  313. detailCtrl.url = [valueDic stringValueForKey:@"url"];
  314. detailCtrl.parmDic = valueDic;
  315. detailCtrl.hiddenNavBar = [valueDic boolValueForKey:@"isHideTitle"];
  316. NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
  317. BOOL isLandScape = orientation == 0 ? YES : NO;
  318. if (isLandScape == self.landScape) {
  319. self.keepOrientation = YES;
  320. detailCtrl.keepOrientation = YES;
  321. }
  322. [self postMessage:parm];
  323. [self.navigationController pushViewController:detailCtrl animated:YES];
  324. }
  325. else {
  326. if (micEnable == PREMISSIONTYPE_NO && cameraEnable == PREMISSIONTYPE_NO) { // 如果麦克风权限和摄像头权限都没有
  327. [self showAlertWithMessage:@"请开启相机和麦克风访问权限" type:CHECKDEVICETYPE_BOTH];
  328. }
  329. else if (micEnable == PREMISSIONTYPE_NO) { // 如果没有麦克风权限
  330. [self showAlertWithMessage:@"请开启麦克风访问权限" type:CHECKDEVICETYPE_MIC];
  331. }
  332. else if (cameraEnable == PREMISSIONTYPE_NO) { // 如果没有摄像头权限
  333. [self showAlertWithMessage:@"请开启相机访问权限" type:CHECKDEVICETYPE_CAMREA];
  334. }
  335. }
  336. }
  337. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"checkAlbum"]) { // 判断权限
  338. [self postMessage:parm];
  339. PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable:NO showInView:nil];
  340. if (albumEnable == PREMISSIONTYPE_NO) {
  341. [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
  342. }
  343. }
  344. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"shareAchievements"]) { // 分享
  345. //
  346. [self shareFunctionWithParm:parm];
  347. }
  348. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"getNavHeight"]) { // 获取状态栏高度和 title heigt
  349. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  350. [valueDic setValue:[NSNumber numberWithFloat:STATUS_GAP*2] forKey:@"navHeight"];
  351. [valueDic setValue:@(44*2) forKey:@"titleHeight"];
  352. [parm setValue:valueDic forKey:@"content"];
  353. [self postMessage:parm];
  354. }
  355. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"backIconChange"]) {
  356. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  357. NSString *backColor = [valueDic stringValueForKey:@"iconStyle"];
  358. NSString *backImage = @"";
  359. if ([backColor isEqualToString:@"black"]) {
  360. backImage = @"back_black";
  361. }
  362. else {
  363. backImage = @"back_button_white";
  364. }
  365. [self.webBackButton.backButton setImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
  366. }
  367. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"setBarStatus"]) { // 顶部是否隐藏
  368. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  369. BOOL isShow = [valueDic boolValueForKey:@"status"]; // 0 隐藏 1 显示
  370. self.hiddenNavBar = !isShow;
  371. CGFloat navHeight = isShow ? kNaviBarHeight : 0;
  372. [self.navView mas_updateConstraints:^(MASConstraintMaker *make) {
  373. make.height.mas_equalTo(navHeight);
  374. }];
  375. [self.myWebView mas_updateConstraints:^(MASConstraintMaker *make) {
  376. make.top.mas_equalTo(self.view.mas_top).offset(navHeight);
  377. }];
  378. }
  379. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"paymentOrder"]) {
  380. NSDictionary *content = [parm dictionaryValueForKey:@"content"];
  381. NSString *channel = [content stringValueForKey:@"payChannel"];
  382. if ([channel isEqualToString:@"ali_app"]) {
  383. NSString *infoMessage = [content stringValueForKey:@"payInfo"];
  384. [KSOrderManager dealWithAliSDK:infoMessage];
  385. }
  386. else if ([channel isEqualToString:@"wx_app"]) {
  387. NSString *infoMessage = [content stringValueForKey:@"payInfo"];
  388. [KSOrderManager dealWithWXSDK:infoMessage];
  389. }
  390. }
  391. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"joinChatGroup"]) {
  392. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  393. NSString *targetId = [valueDic stringValueForKey:@"id"];
  394. if ([valueDic stringValueForKey:@"single"]) { // 单聊
  395. KSChatConversationViewController *ctrl = [[KSChatConversationViewController alloc] init];
  396. ctrl.targetId = targetId;
  397. ctrl.conversationType = ConversationType_PRIVATE;
  398. [self.navigationController pushViewController:ctrl animated:YES];
  399. }
  400. else if ([valueDic stringValueForKey:@"multi"]) { // 群聊
  401. KSChatConversationViewController *ctrl = [[KSChatConversationViewController alloc] init];
  402. ctrl.targetId = targetId;
  403. ctrl.conversationType = ConversationType_GROUP;
  404. [self.navigationController pushViewController:ctrl animated:YES];
  405. }
  406. }
  407. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"setAddress"]) { // 跳转地址选择
  408. AddressListViewController *ctrl = [[AddressListViewController alloc] init];
  409. ctrl.isChooseAddress = YES;
  410. MJWeakSelf;
  411. [ctrl chooseAddressAction:^(AddressListModel * _Nonnull model) {
  412. [weakSelf sendAddressAction:model];
  413. }];
  414. [self.navigationController pushViewController:ctrl animated:YES];
  415. }
  416. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"joinLiveRoom"]) { // 进入直播间
  417. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  418. NSString *roomId = [valueDic stringValueForKey:@"roomId"];
  419. [self showhud];
  420. [KSEnterLiveroomManager joinLiveWithRoomId:roomId inController:(CustomNavViewController *)self.navigationController callback:^{
  421. [self removehub];
  422. }];
  423. }
  424. }
  425. - (void)sendAddressAction:(AddressListModel *)model {
  426. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  427. [sendParm setValue:@"getAddress" forKey:@"api"];
  428. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  429. [content setValue:model.internalBaseClassIdentifier forKey:@"id"];
  430. [content setValue:model.detailAddress forKey:@"detailAddress"];
  431. [content setValue:model.city forKey:@"city"];
  432. [content setValue:model.region forKey:@"region"];
  433. [content setValue:model.province forKey:@"province"];
  434. [content setValue:model.name forKey:@"name"];
  435. [content setValue:model.phoneNumber forKey:@"phoneNumber"];
  436. [content setValue:model.postCode forKey:@"postCode"];
  437. [sendParm setValue:content forKey:@"content"];
  438. [self postMessage:sendParm];
  439. }
  440. - (UIImage *)imageWithBase64String:(NSString *)base64String {
  441. NSURL *URL = [NSURL URLWithString:base64String];
  442. NSData *imageData = [NSData dataWithContentsOfURL:URL];
  443. UIImage *image = [UIImage imageWithData:imageData scale:2];
  444. return image;
  445. }
  446. - (void)shareFunctionWithParm:(NSDictionary *)parm {
  447. // NSDictionary *content = [parm dictionaryValueForKey:@"content"];
  448. // NSString *typeString = [content stringValueForKey:@"type"];
  449. // KSSHARETYPE shareType = [typeString isEqualToString:@"image"] ? KSSHARETYPE_IMAGE : KSSHARETYPE_VODEO;
  450. // NSString *shareTitle = [content stringValueForKey:@"title"];
  451. // NSString *descMessage = [content stringValueForKey:@"desc"];
  452. // NSString *videoUrl = [content stringValueForKey:@"video"];
  453. // NSString *imgStr = [content stringValueForKey:@"image"];
  454. // UIImage *shareImage = [self imageWithBase64String:imgStr];
  455. // [KSUMShareManager shareInstanceWithImage:shareImage url:videoUrl shareTitle:shareTitle descMessage:descMessage shareType:shareType showInView:self callback:^(BOOL isSuccess, NSString *descMessage) {
  456. // NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  457. // [responParm setValue:[parm stringValueForKey:@"api"] forKey:@"api"];
  458. // NSMutableDictionary *content = [NSMutableDictionary dictionary];
  459. // [content setValue:[content stringValueForKey:@"UUID"] forKey:@"content"];
  460. // [content setValue:descMessage forKey:@"message"];
  461. // BOOL status = isSuccess;
  462. // [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  463. // [responParm setValue:content forKey:@"content"];
  464. // [self postMessage:responParm];
  465. // }];
  466. }
  467. - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
  468. [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
  469. } confirm:^{
  470. [self openSettingView];
  471. }];
  472. }
  473. - (void)openSettingView {
  474. if (@available(iOS 10, *)) {
  475. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
  476. } else {
  477. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  478. }
  479. }
  480. - (void)displaySource:(NSURL *)localUrl {
  481. KSLocalWebViewController *ctrl = [[KSLocalWebViewController alloc] init];
  482. ctrl.headTitle = @"协议文件";
  483. ctrl.sourceData = [NSData dataWithContentsOfURL:localUrl];
  484. ctrl.fileUrl = localUrl;
  485. [self.navigationController pushViewController:ctrl animated:YES];
  486. }
  487. - (void)postMessage:(NSDictionary *)parm {
  488. if (_myWebView) {
  489. dispatch_async(dispatch_get_main_queue(), ^{
  490. NSString *jsString = [parm mj_JSONString];
  491. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"postMessage(%@,'*')", jsString] completionHandler:nil];
  492. });
  493. }
  494. }
  495. // 刷新
  496. - (void)refreshUrl:(NSString *)refreshUrl {
  497. NSString *sepectString = [refreshUrl containsString:@"?"] ? @"&" : @"?";
  498. NSString *tokenStr = UserDefault(TokenKey);
  499. if (![NSString isEmptyString:tokenStr]) {
  500. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  501. refreshUrl = [NSString stringWithFormat:@"%@%@%@",refreshUrl, sepectString, token];
  502. }
  503. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:refreshUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  504. [self.myWebView loadRequest:request];
  505. }
  506. // 返回登录页面
  507. - (void)backLoginView {
  508. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  509. [RCConnectionManager shareManager].isNeedJoin = NO;
  510. [RCConnectionManager shareManager].isNeedShowMessage = NO;
  511. [[RCIM sharedRCIM] logout];
  512. NSString *webUrl = [self.url copy];
  513. if ([webUrl containsString:@"Authorization="]) {
  514. NSRange range = [webUrl rangeOfString:@"Authorization="];
  515. if (range.location != NSNotFound) {
  516. webUrl = [webUrl substringToIndex:range.location-1];
  517. }
  518. }
  519. // 获取次数
  520. NSString *failCount = UserDefault(@"WEB_FAILCOUNT");
  521. if ([NSString isEmptyString:failCount]) {
  522. failCount = @"1";
  523. UserDefaultSetObjectForKey(failCount, @"WEB_FAILCOUNT");
  524. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  525. }
  526. else if (failCount.integerValue == 1) {
  527. NSString *preUrl = UserDefaultObjectForKey(FAIL_WEB_URL);
  528. if (![webUrl isEqualToString:preUrl]) { // 如果打开和之前失败不相同重新统计数据
  529. UserDefaultSetObjectForKey(@"1", @"WEB_FAILCOUNT");
  530. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  531. }
  532. else {
  533. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  534. }
  535. }
  536. else {
  537. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  538. }
  539. // 当前失败的H5地址
  540. UserDefaultSetObjectForKey(webUrl, FAIL_WEB_URL);
  541. // 取消推送别名
  542. [JPUSHService deleteAlias:nil seq:0];
  543. [[NSUserDefaults standardUserDefaults] removeObjectForKey:TokenKey];
  544. [[NSUserDefaults standardUserDefaults] removeObjectForKey:Token_type];
  545. [[NSUserDefaults standardUserDefaults] removeObjectForKey:RongTokenKey];
  546. [[NSUserDefaults standardUserDefaults] removeObjectForKey:RefreshToken];
  547. [KSNetworkingManager clearRequestHeader];
  548. LoginViewController *loginVC = [[LoginViewController alloc] init];
  549. CustomNavViewController *navCtrl = [[CustomNavViewController alloc] initWithRootViewController:loginVC];
  550. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  551. appDelegate.window.rootViewController = navCtrl;
  552. }
  553. #pragma mark ----- WKWebView delegate
  554. // 1 在发送请求之前,决定是否跳转
  555. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  556. NSLog(@"1-------在发送请求之前,决定是否跳转 -->%@",navigationAction.request);
  557. NSURL *url = navigationAction.request.URL;
  558. NSString *scheme = [url scheme];
  559. UIApplication *app = [UIApplication sharedApplication];
  560. NSString *urlString = url.absoluteString;
  561. if (![urlString containsString:@"colexiu.com"] && ![urlString containsString:WEBHOST]) { // 外部链接
  562. self.isOutLink = YES;
  563. }
  564. else {
  565. self.isOutLink = NO;
  566. }
  567. // 打电话
  568. if ([scheme isEqualToString:@"tel"]) {
  569. if ([app canOpenURL:url]) {
  570. [app openURL:url];
  571. // 一定要加上这句,否则会打开新页面
  572. decisionHandler(WKNavigationActionPolicyCancel);
  573. return;
  574. }
  575. }
  576. decisionHandler(WKNavigationActionPolicyAllow);
  577. }
  578. // 2 页面开始加载时调用
  579. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  580. NSLog(@"2-------页面开始加载时调用");
  581. }
  582. // 3 在收到响应后,决定是否跳转
  583. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  584. /// 在收到服务器的响应头,根据response相关信息,决定是否跳转。decisionHandler必须调用,来决定是否跳转,参数WKNavigationActionPolicyCancel取消跳转,WKNavigationActionPolicyAllow允许跳转
  585. NSLog(@"3-------在收到响应后,决定是否跳转");
  586. decisionHandler(WKNavigationResponsePolicyAllow);
  587. }
  588. // 4 当内容开始返回时调用
  589. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
  590. NSLog(@"4-------当内容开始返回时调用");
  591. }
  592. // 5 页面加载完成之后调用
  593. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  594. NSLog(@"5-------页面加载完成之后调用");
  595. if (_hasModify == NO) {
  596. [self configLocalStorage];
  597. }
  598. }
  599. // 调用js方法
  600. - (void)postMessageJS:(NSDictionary *)jsDict {
  601. NSString *jsString = [jsDict mj_JSONString];
  602. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"sendMessage(%@)", jsString] completionHandler:nil];
  603. }
  604. // 6 页面加载失败时调用
  605. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
  606. NSLog(@"6-------页面加载失败时调用");
  607. }
  608. // 接收到服务器跳转请求之后调用
  609. - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
  610. NSLog(@"-------接收到服务器跳转请求之后调用");
  611. }
  612. // 数据加载发生错误时调用
  613. - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
  614. NSLog(@"----数据加载发生错误时调用");
  615. }
  616. - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
  617. {
  618. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  619. if (challenge.previousFailureCount == 0) {
  620. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  621. completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
  622. } else {
  623. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  624. }
  625. }
  626. }
  627. //当因为某些问题,导致webView进程终止时触发
  628. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
  629. NSLog(@"%s", __func__);
  630. [webView reload];
  631. }
  632. /**
  633. * web界面中有弹出警告框时调用
  634. *
  635. * @param webView 实现该代理的webview
  636. * @param message 警告框中的内容
  637. * @param completionHandler 警告框消失调用
  638. */
  639. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
  640. NSLog(@"-------web界面中有弹出警告框时调用");
  641. NSLog(@"%@",message);
  642. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  643. message:nil
  644. preferredStyle:UIAlertControllerStyleAlert];
  645. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  646. style:UIAlertActionStyleCancel
  647. handler:^(UIAlertAction *action) {
  648. completionHandler();
  649. }]];
  650. [self presentViewController:alertController animated:YES completion:nil];
  651. }
  652. // 取消和确认的按钮
  653. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
  654. // js 里面的alert实现,如果不实现,网页的alert函数无效 ,
  655. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  656. message:nil
  657. preferredStyle:UIAlertControllerStyleAlert];
  658. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  659. style:UIAlertActionStyleDefault
  660. handler:^(UIAlertAction *action) {
  661. completionHandler(YES);
  662. }]];
  663. [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
  664. style:UIAlertActionStyleCancel
  665. handler:^(UIAlertAction *action){
  666. completionHandler(NO);
  667. }]];
  668. [self presentViewController:alertController animated:YES completion:^{}];
  669. }
  670. #pragma mark - KVO回馈
  671. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  672. if ([keyPath isEqualToString:@"estimatedProgress"]) {
  673. self.progressLayer.opacity = 1;
  674. if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
  675. return;
  676. }
  677. self.progressLayer.frame = CGRectMake(0, 0, kScreenWidth*[change[@"new"] floatValue], 3);
  678. if ([change[@"new"]floatValue] == 1.0) {
  679. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  680. self.progressLayer.opacity = 0;
  681. self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
  682. });
  683. }
  684. }else if ([keyPath isEqualToString:@"title"]) {
  685. // 顶部title
  686. self.headTitle = change[@"new"];
  687. if (self.hiddenNavBar == NO) {
  688. self.navView.topTitleLabel.text = self.headTitle;
  689. }
  690. }
  691. }
  692. /*
  693. #pragma mark - Navigation
  694. // In a storyboard-based application, you will often want to do a little preparation before navigation
  695. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  696. // Get the new view controller using [segue destinationViewController].
  697. // Pass the selected object to the new view controller.
  698. }
  699. */
  700. - (void)configLocalStorage {
  701. _hasModify = YES;
  702. if (![NSString isEmptyString:UserDefault(TokenKey)]) {
  703. NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('Authorization', '%@ %@')",UserDefault(Token_type), UserDefault(TokenKey)];
  704. [self.myWebView evaluateJavaScript:jsString completionHandler:nil];
  705. }
  706. }
  707. - (void)setupProgress {
  708. UIView *progress = [[UIView alloc]init];
  709. progress.frame = CGRectMake(0, 0, kScreenWidth, 3);
  710. progress.backgroundColor = [UIColor clearColor];
  711. [self.view addSubview:progress];
  712. CALayer *layer = [CALayer layer];
  713. layer.frame = CGRectMake(0, 0, 0, 3);
  714. layer.backgroundColor = THEMECOLOR.CGColor;
  715. [progress.layer addSublayer:layer];
  716. self.progressLayer = layer;
  717. }
  718. + (WKProcessPool*)singleWkProcessPool {
  719. static WKProcessPool *sharedPool;
  720. static dispatch_once_t onceToken;
  721. dispatch_once(&onceToken, ^{
  722. sharedPool = [[WKProcessPool alloc] init];
  723. });
  724. return sharedPool;
  725. }
  726. - (NSDictionary *)convertJsonStringToNSDictionary:(NSString *)jsonString {
  727. if (jsonString == nil) {
  728. return nil;
  729. }
  730. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  731. NSError *error;
  732. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
  733. if (error) {
  734. NSLog(@"jsonString解析失败:%@", error);
  735. return nil;
  736. }
  737. return json;
  738. }
  739. - (void)setHiddenNavBar:(BOOL)hiddenNavBar {
  740. _hiddenNavBar = hiddenNavBar;
  741. if (hiddenNavBar) {
  742. self.navView.topTitleLabel.text = @"";
  743. }
  744. else {
  745. self.navView.topTitleLabel.text = self.headTitle;
  746. }
  747. }
  748. #pragma mark --- lazying
  749. - (KSWebNavView *)navView {
  750. if (!_navView) {
  751. _navView = [[KSWebNavView alloc] init];
  752. }
  753. return _navView;
  754. }
  755. - (KSWebBackButton *)webBackButton {
  756. if (!_webBackButton) {
  757. _webBackButton = [[KSWebBackButton alloc] init];
  758. MJWeakSelf;
  759. [_webBackButton webViewBackAction:^{
  760. [weakSelf backAction];
  761. }];
  762. }
  763. return _webBackButton;
  764. }
  765. - (void)dealloc {
  766. [[_myWebView configuration].userContentController removeScriptMessageHandlerForName:@"COLEXIU"];
  767. [_myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
  768. [_myWebView removeObserver:self forKeyPath:@"title"];
  769. [_myWebView loadHTMLString:@"" baseURL:nil];
  770. [_myWebView removeFromSuperview];
  771. _myWebView = nil;
  772. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  773. [[NSURLCache sharedURLCache] setDiskCapacity:0];
  774. [[NSURLCache sharedURLCache] setMemoryCapacity:0];
  775. [[NSNotificationCenter defaultCenter] removeObserver:self];
  776. }
  777. - (NSString *)getSaveSpeedPath {
  778. // 在Documents目录下创建一个名为AudioSpeedFile的文件夹
  779. NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioSpeedFile"];
  780. NSLog(@"%@",path);
  781. NSFileManager *fileManager = [NSFileManager defaultManager];
  782. BOOL isDir = FALSE;
  783. BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
  784. if(!(isDirExist && isDir)) {
  785. BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  786. if(!bCreateDir){
  787. NSLog(@"创建文件夹失败!");
  788. }
  789. NSLog(@"创建文件夹成功,文件路径%@",path);
  790. }
  791. path = [path stringByAppendingPathComponent:@"songSpeed.plist"];
  792. NSLog(@"file path:%@",path);
  793. return path;
  794. }
  795. /*
  796. #pragma mark - Navigation
  797. // In a storyboard-based application, you will often want to do a little preparation before navigation
  798. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  799. // Get the new view controller using [segue destinationViewController].
  800. // Pass the selected object to the new view controller.
  801. }
  802. */
  803. @end