KSBaseWKWebViewController.m 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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 "UIDevice+TFDevice.h"
  13. #import "KSPremissionAlert.h"
  14. #import "RecordCheckManager.h"
  15. #import "KSLocalWebViewController.h"
  16. #import "KSAccompanyWebViewController.h"
  17. #import "KSChatConversationViewController.h"
  18. #import "KSGroupConversationController.h"
  19. #import "KSOrderManager.h"
  20. #import "AddressListViewController.h"
  21. #import "KSEnterLiveroomManager.h"
  22. #import "TZImageManager.h"
  23. #import <AVFoundation/AVFoundation.h>
  24. #import "KSDocumentViewController.h"
  25. #import "KSICloudManager.h"
  26. #import "KSMediaManager.h"
  27. #import "KSUMShareManager.h"
  28. #import "UserInfoManager.h"
  29. #import "KSWebLoadRefreshView.h"
  30. typedef NS_ENUM(NSInteger, CHOOSETYPE) {
  31. CHOOSETYPE_XML,
  32. CHOOSETYPE_MIDI,
  33. CHOOSETYPE_MP3,
  34. CHOOSETYPE_ALL,
  35. };
  36. @interface KSBaseWKWebViewController ()<UIDocumentPickerDelegate>
  37. @property (nonatomic, assign) BOOL isOutLink; // 外部链接
  38. @property (nonatomic,weak) CALayer *progressLayer;
  39. @property (nonatomic, strong) NSString *currerntURL; // 当前web URL
  40. @property (nonatomic, assign) BOOL hasModify;
  41. @property (nonatomic, assign) BOOL hasChangeSource; // 是否切换了亮屏,横屏等配置
  42. @property (nonatomic, assign) BOOL landScape;
  43. /// 选择本地文件 parm
  44. @property (nonatomic, strong) NSMutableDictionary *chooseFileParm;
  45. @property (nonatomic, strong) KSMediaManager *mediaManager;
  46. @property (strong, nonatomic) MBProgressHUD *HUD;
  47. @property (nonatomic, assign) CHOOSETYPE fileChooseType;
  48. @property (nonatomic, strong) NSString *bucketName;
  49. @property (nonatomic, assign) BOOL isFirstLoad;
  50. @property (nonatomic, strong) KSWebLoadRefreshView *errorView;
  51. @end
  52. @implementation KSBaseWKWebViewController
  53. - (void)viewDidLoad {
  54. [super viewDidLoad];
  55. // Do any additional setup after loading the view.
  56. self.ks_prefersNavigationBarHidden = YES; // 隐藏导航栏,其他事件额外处理
  57. [self initWebView];
  58. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(operationDealCallbackMessage:) name:DEALCALLBACKNOTICIFATION object:nil];
  59. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backLoginView) name:@"liveroomBackRefresh" object:nil];
  60. self.isFirstLoad = YES;
  61. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(captureViewTips:) name:UIScreenCapturedDidChangeNotification object:nil];
  62. }
  63. - (void)captureViewTips:(NSNotification *)notification {
  64. [self checkCaptured];
  65. }
  66. - (void)checkCaptured {
  67. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  68. if ([self checkIsCaptured]) {
  69. [self didCapturedView];
  70. }
  71. });
  72. }
  73. #pragma mark ---- 镜像和投屏检测
  74. - (BOOL)checkIsCaptured {
  75. if ([UIScreen mainScreen].isCaptured && [UIScreen screens].count < 2) {
  76. return YES;
  77. }
  78. return NO;
  79. }
  80. - (void)didCapturedView {
  81. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  82. [sendParm setValue:@"setVideoPlayer" forKey:@"api"];
  83. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  84. [content setValue:@"pause" forKey:@"status"];
  85. [sendParm setValue:content forKey:@"content"];
  86. [self postMessage:sendParm];
  87. }
  88. - (void)operationDealCallbackMessage:(NSNotification *)notification {
  89. NSString *status = [notification object];
  90. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  91. [sendParm setValue:@"paymentOperation" forKey:@"api"];
  92. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  93. [content setValue:status forKey:@"status"];
  94. [sendParm setValue:content forKey:@"content"];
  95. [self postMessage:sendParm];
  96. }
  97. - (void)setParmDic:(NSDictionary *)parmDic {
  98. _parmDic = parmDic;
  99. _hasChangeSource = YES;
  100. BOOL isOpenLight = [parmDic ks_boolValueForKey:@"isOpenLight"];
  101. [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
  102. // 横竖屏
  103. NSInteger orientation = [parmDic ks_integerValueForKey:@"orientation"];
  104. BOOL isLandScape = orientation == 0 ? YES : NO;
  105. self.ks_landScape = isLandScape;
  106. [self changeOrientation:isLandScape];
  107. }
  108. - (void)changeOrientation:(BOOL)isLandScape {
  109. if (isLandScape) {
  110. // 切换到横屏
  111. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  112. delegate.allowAutoRotate = YES;
  113. [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight inController:self];
  114. }
  115. else {
  116. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  117. delegate.allowAutoRotate = NO;
  118. [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait inController:self];
  119. }
  120. }
  121. - (void)viewWillAppear:(BOOL)animated {
  122. [super viewWillAppear:animated];
  123. if (_hasChangeSource) {
  124. [self setParmDic:self.parmDic];
  125. }
  126. if (self.isFirstLoad == NO) {
  127. [self sendResumeMessage];
  128. }
  129. self.isFirstLoad = NO;
  130. if ([UIScreen mainScreen].isCaptured) {
  131. [self didCapturedView];
  132. }
  133. }
  134. - (void)sendResumeMessage {
  135. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  136. [parm setValue:@"webViewOnResume" forKey:@"api"];
  137. [self postMessage:parm];
  138. }
  139. - (void)viewWillDisappear:(BOOL)animated {
  140. [super viewWillDisappear:animated];
  141. BOOL isBack = [self isViewPopDismiss];
  142. if (isBack) {
  143. if (self.preCtrl) {
  144. if (self.ks_landScape != self.preCtrl.ks_landScape) {
  145. [self changeOrientation:self.preCtrl.ks_landScape];
  146. }
  147. }
  148. if (![self.preCtrl isKindOfClass:[KSBaseWKWebViewController class]]) {
  149. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  150. }
  151. }
  152. else {
  153. KSBaseViewController *nextCtrl = [self getNextViewController];
  154. if (nextCtrl) {
  155. if (nextCtrl.ks_landScape != self.ks_landScape) {
  156. [self changeOrientation:NO];
  157. }
  158. }
  159. }
  160. }
  161. - (void)initWebView {
  162. [self.scrollView removeFromSuperview];
  163. if (_myWebView == nil) {
  164. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  165. config.selectionGranularity = WKSelectionGranularityDynamic;
  166. config.allowsInlineMediaPlayback = YES;
  167. config.mediaTypesRequiringUserActionForPlayback = NO;
  168. config.processPool = [KSBaseWKWebViewController singleWkProcessPool];
  169. config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  170. [self configUserAgent:config];
  171. //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
  172. WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
  173. //这个类主要用来做native与JavaScript的交互管理
  174. WKUserContentController * wkUController = [[WKUserContentController alloc] init];
  175. [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"COLEXIU"];
  176. config.userContentController = wkUController;
  177. WKPreferences *preferences = [WKPreferences new];
  178. // 是否支出javaScript
  179. preferences.javaScriptEnabled = YES;
  180. //不通过用户交互,是否可以打开窗口
  181. preferences.javaScriptCanOpenWindowsAutomatically = YES;
  182. config.preferences = preferences;
  183. _myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
  184. _myWebView.UIDelegate = self;
  185. _myWebView.navigationDelegate = self;
  186. _myWebView.scrollView.bounces = NO;
  187. _myWebView.scrollView.showsVerticalScrollIndicator = NO;
  188. _myWebView.scrollView.showsHorizontalScrollIndicator = NO;
  189. // 加载进度条和title
  190. [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  191. [self.view addSubview:_myWebView];
  192. // // OC
  193. // if (@available(iOS 16.4, *)) {
  194. // _myWebView.inspectable = true;
  195. // } else {
  196. // // Fallback on earlier versions
  197. // }
  198. [_myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
  199. make.left.right.mas_equalTo(self.view);
  200. make.top.mas_equalTo(self.view.mas_top);
  201. make.bottom.mas_equalTo(self.view.mas_bottom);
  202. }];
  203. if (@available(iOS 11.0, *)) {
  204. _myWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  205. } else {
  206. // Fallback on earlier versions
  207. }
  208. [self setupProgress];
  209. // 修改userAgent
  210. [self loadRequest];
  211. }
  212. else {
  213. [_myWebView reload];
  214. }
  215. }
  216. - (void)configUserAgent:(WKWebViewConfiguration *)config {
  217. NSString *oldUserAgent = config.applicationNameForUserAgent;
  218. NSString *newAgent = [NSString stringWithFormat:@"%@ %@ %@",oldUserAgent,@"COLEXIUAPPI",@"COLEXIUSTUDENT"];
  219. config.applicationNameForUserAgent = newAgent;
  220. }
  221. - (void)loadRequest {
  222. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  223. [self.myWebView loadRequest:request];
  224. }
  225. - (NSString *)url {
  226. if (_url) {
  227. if ([_url containsString:@"Authorization="]) {
  228. NSRange range = [_url rangeOfString:@"Authorization="];
  229. if (range.location != NSNotFound) {
  230. _url = [_url substringToIndex:range.location-1];
  231. }
  232. }
  233. NSString *sepectString = [_url containsString:@"?"] ? @"&" : @"?";
  234. NSString *tokenStr = UserDefault(TokenKey);
  235. if (![NSString isEmptyString:tokenStr]) {
  236. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  237. _url = [NSString stringWithFormat:@"%@%@%@",_url, sepectString, token];
  238. }
  239. }
  240. return _url;
  241. }
  242. #pragma mark --- 返回按钮的处理
  243. - (void)backAction {
  244. [self.myWebView stopLoading];
  245. if (_backRootView) {
  246. [self.navigationController popToRootViewControllerAnimated:NO];
  247. return;
  248. }
  249. else if (_isBackPreView) {
  250. [self.navigationController popViewControllerAnimated:YES];
  251. return;
  252. }
  253. else if ([self.myWebView canGoBack]) {
  254. [self.myWebView goBack];
  255. }
  256. else {
  257. [self.navigationController popViewControllerAnimated:YES];
  258. }
  259. }
  260. #pragma mark - WKScriptMessageHandler
  261. - (void)userContentController:(WKUserContentController *)userContentController
  262. didReceiveScriptMessage:(WKScriptMessage *)message {
  263. if ([message.name isEqualToString:@"COLEXIU"]) {
  264. NSDictionary *parm = [self convertJsonStringToNSDictionary:message.body];
  265. // 回到主线程
  266. dispatch_async(dispatch_get_main_queue(), ^{
  267. [self handleScriptMessageSource:parm];
  268. });
  269. }
  270. }
  271. - (void)handleScriptMessageSource:(NSDictionary *)parm {
  272. if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"back"]) { // 返回
  273. [self.myWebView stopLoading];
  274. [self.navigationController popViewControllerAnimated:YES];
  275. }
  276. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"goBack"]) { // 逐级返回
  277. [self backAction];
  278. }
  279. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"login"]) {
  280. // 回到登录页面
  281. [self backLoginView];
  282. }
  283. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openWebView"]) { // 打开新页面
  284. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  285. KSBaseWKWebViewController *detailCtrl = [[KSBaseWKWebViewController alloc] init];
  286. detailCtrl.url = [valueDic ks_stringValueForKey:@"url"];
  287. detailCtrl.parmDic = valueDic;
  288. NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
  289. BOOL isLandScape = orientation == 0 ? YES : NO;
  290. if (isLandScape == self.landScape) {
  291. self.keepOrientation = YES;
  292. detailCtrl.keepOrientation = YES;
  293. }
  294. [self postMessage:parm];
  295. [self.navigationController pushViewController:detailCtrl animated:YES];
  296. }
  297. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setRequestedOrientation"]) {
  298. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  299. // 横竖屏
  300. NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
  301. BOOL isLandScape = orientation == 0 ? YES : NO;
  302. self.ks_landScape = isLandScape;
  303. [self changeOrientation:isLandScape];
  304. }
  305. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"keepScreenLongLight"]) {
  306. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  307. BOOL isOpenLight = [valueDic ks_boolValueForKey:@"isOpenLight"];
  308. [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
  309. }
  310. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"downLoad"]) {
  311. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  312. if ([valueDic ks_stringValueForKey:@"PDF"]) {
  313. NSString *url = [valueDic ks_stringValueForKey:@"downloadUrl"];
  314. [KSNetworkingManager downloadFileRequestWithFileUrl:url progress:^(int64_t bytesRead, int64_t totalBytes) {
  315. } success:^(NSURL * _Nonnull fileUrl) {
  316. [LOADING_MANAGER KSShowMsg:@"下载成功" promptCompletion:^{
  317. [self displaySource:fileUrl];
  318. }];
  319. } faliure:^(NSError * _Nonnull error) {
  320. }];
  321. }
  322. }
  323. // 回调是否刘海屏
  324. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"isSpecialShapedScreen"]) {
  325. BOOL isShapedScreen = iPhoneXSafeTopMargin > 0 ? YES : NO;
  326. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  327. [valueDic setValue:@(isShapedScreen) forKey:@"isSpecialShapedScreen"];
  328. [valueDic setValue:@(iPhoneXSafeTopMargin*2) forKey:@"notchHeight"];
  329. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  330. [sendParm setValue:valueDic forKey:@"content"];
  331. [self postMessage:sendParm];
  332. }
  333. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getToken"]) {
  334. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  335. [valueDic setValue:UserDefault(Token_type) forKey:@"tokenType"];
  336. [valueDic setValue:UserDefault(TokenKey) forKey:@"accessToken"];
  337. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  338. [sendParm setValue:valueDic forKey:@"content"];
  339. [self postMessage:sendParm];
  340. }
  341. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openAccompanyWebView"]) { // 打开伴奏
  342. PREMISSIONTYPE micEnable = [RecordCheckManager checkPermissionShowAlert:NO showInView:nil];
  343. PREMISSIONTYPE cameraEnable = [RecordCheckManager checkCameraPremissionAvaiable:NO showInView:nil];
  344. if (micEnable == PREMISSIONTYPE_YES && cameraEnable == PREMISSIONTYPE_YES) { // 如果麦克风和摄像头权限都有
  345. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  346. KSAccompanyWebViewController *detailCtrl = [[KSAccompanyWebViewController alloc] init];
  347. detailCtrl.url = [valueDic ks_stringValueForKey:@"url"];
  348. detailCtrl.parmDic = valueDic;
  349. NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
  350. BOOL isLandScape = orientation == 0 ? YES : NO;
  351. detailCtrl.ks_landScape = isLandScape;
  352. [self postMessage:parm];
  353. [self.navigationController pushViewController:detailCtrl animated:YES];
  354. }
  355. else {
  356. if (micEnable == PREMISSIONTYPE_NO && cameraEnable == PREMISSIONTYPE_NO) { // 如果麦克风权限和摄像头权限都没有
  357. [self showAlertWithMessage:@"请开启相机和麦克风访问权限" type:CHECKDEVICETYPE_BOTH];
  358. }
  359. else if (micEnable == PREMISSIONTYPE_NO) { // 如果没有麦克风权限
  360. [self showAlertWithMessage:@"请开启麦克风访问权限" type:CHECKDEVICETYPE_MIC];
  361. }
  362. else if (cameraEnable == PREMISSIONTYPE_NO) { // 如果没有摄像头权限
  363. [self showAlertWithMessage:@"请开启相机访问权限" type:CHECKDEVICETYPE_CAMREA];
  364. }
  365. }
  366. }
  367. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"checkAlbum"]) { // 判断权限
  368. [self postMessage:parm];
  369. PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable:NO showInView:nil];
  370. if (albumEnable == PREMISSIONTYPE_NO) {
  371. [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
  372. }
  373. }
  374. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"shareAchievements"]) { // 分享
  375. //
  376. [self shareFunctionWithParm:parm];
  377. }
  378. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getNavHeight"]) { // 获取状态栏高度和 title heigt
  379. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  380. [valueDic setValue:[NSNumber numberWithFloat:STATUS_GAP*2] forKey:@"navHeight"];
  381. [valueDic setValue:@(44*2) forKey:@"titleHeight"];
  382. [parm setValue:valueDic forKey:@"content"];
  383. [self postMessage:parm];
  384. }
  385. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"backIconChange"]) {
  386. /*
  387. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  388. NSString *backColor = [valueDic ks_stringValueForKey:@"iconStyle"];
  389. NSString *backImage = @"";
  390. if ([backColor isEqualToString:@"black"]) {
  391. backImage = @"back_black";
  392. }
  393. else {
  394. backImage = @"back_button_white";
  395. }
  396. [self.webBackButton.backButton setImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
  397. // 是否隐藏按钮
  398. BOOL hideButton = [valueDic ks_boolValueForKey:@"backIconHide"];
  399. self.webBackButton.hidden = hideButton;
  400. */
  401. }
  402. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setBarStatus"]) { // 顶部是否隐藏
  403. /*
  404. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  405. BOOL isShow = [valueDic ks_boolValueForKey:@"status"]; // 0 隐藏 1 显示
  406. self.hiddenNavBar = !isShow;
  407. CGFloat navHeight = isShow ? kNaviBarHeight : 0;
  408. [self.navView mas_updateConstraints:^(MASConstraintMaker *make) {
  409. make.height.mas_equalTo(navHeight);
  410. }];
  411. [self.myWebView mas_updateConstraints:^(MASConstraintMaker *make) {
  412. make.top.mas_equalTo(self.view.mas_top).offset(navHeight);
  413. }];
  414. */
  415. }
  416. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setStatusBarTextColor"]) { // 设置状态栏颜色
  417. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  418. BOOL whiteColor = [valueDic ks_boolValueForKey:@"statusBarTextColor"];
  419. if (whiteColor) {
  420. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  421. }
  422. else {
  423. if (@available(iOS 13.0, *)) {
  424. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
  425. } else {
  426. // Fallback on earlier versions
  427. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
  428. }
  429. }
  430. }
  431. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"paymentOrder"]) {
  432. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  433. NSString *channel = [content ks_stringValueForKey:@"payChannel"];
  434. if ([channel isEqualToString:@"ali_app"]) {
  435. NSString *infoMessage = [content ks_stringValueForKey:@"payInfo"];
  436. [KSOrderManager dealWithAliSDK:infoMessage];
  437. }
  438. else if ([channel isEqualToString:@"wx_app"]) {
  439. NSString *infoMessage = [content ks_stringValueForKey:@"payInfo"];
  440. [KSOrderManager dealWithWXSDK:infoMessage];
  441. }
  442. }
  443. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"joinChatGroup"]) {
  444. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  445. NSString *targetId = [valueDic ks_stringValueForKey:@"id"];
  446. if ([[valueDic ks_stringValueForKey:@"type"] isEqualToString:@"single"]) { // 单聊
  447. TUIChatConversationModel *model = [[TUIChatConversationModel alloc] init];
  448. model.userID = targetId;
  449. KSChatConversationViewController *ctrl = [[KSChatConversationViewController alloc] init];
  450. ctrl.conversation = model;
  451. [self.navigationController pushViewController:ctrl animated:YES];
  452. }
  453. else if ([[valueDic ks_stringValueForKey:@"type"] isEqualToString:@"multi"]) { // 群聊
  454. if ([NSString isEmptyString:targetId]) {
  455. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"报名未结束,暂无群组"];
  456. return;
  457. }
  458. TUIChatConversationModel *model = [[TUIChatConversationModel alloc] init];
  459. model.groupID = targetId;
  460. KSGroupConversationController *ctrl = [[KSGroupConversationController alloc] init];
  461. ctrl.conversation = model;
  462. [self.navigationController pushViewController:ctrl animated:YES];
  463. }
  464. }
  465. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"chooseFile"]) {
  466. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  467. self.chooseFileParm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
  468. NSString *typeStr = [valueDic ks_stringValueForKey:@"type"];
  469. NSInteger maxCount = [valueDic ks_integerValueForKey:@"max"];
  470. NSString *bucket = [valueDic ks_stringValueForKey:@"bucket"];
  471. [self chooseFileWithType:typeStr maxNumber:maxCount bucket:bucket];
  472. }
  473. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setAddress"]) { // 跳转地址选择
  474. AddressListViewController *ctrl = [[AddressListViewController alloc] init];
  475. ctrl.isChooseAddress = YES;
  476. MJWeakSelf;
  477. [ctrl chooseAddressAction:^(AddressListModel * _Nonnull model) {
  478. [weakSelf sendAddressAction:model];
  479. }];
  480. [self.navigationController pushViewController:ctrl animated:YES];
  481. }
  482. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"joinLiveRoom"]) { // 进入直播间
  483. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  484. NSString *roomId = [valueDic ks_stringValueForKey:@"roomId"];
  485. [LOADING_MANAGER showHUD];
  486. [KSEnterLiveroomManager joinLiveWithRoomId:roomId inController:(CustomNavViewController *)self.navigationController callback:^{
  487. [LOADING_MANAGER removeHUD];
  488. }];
  489. }
  490. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"savePicture"]) { // 保存图片到相册
  491. // 判断相册权限
  492. PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable:NO showInView:nil];
  493. if (albumEnable == PREMISSIONTYPE_YES) { // 如果有权限
  494. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  495. NSString *base64String = [valueDic ks_stringValueForKey:@"base64"];
  496. UIImage *saveImage = [self imageWithBase64String:base64String];
  497. [[TZImageManager manager] savePhotoWithImage:saveImage completion:^(PHAsset *asset, NSError *error) {
  498. if (!error) {
  499. [self savePicCallback:[valueDic ks_stringValueForKey:@"uuid"] isSuccess:YES];
  500. }
  501. else {
  502. [self savePicCallback:[valueDic ks_stringValueForKey:@"uuid"] isSuccess:NO];
  503. }
  504. }];
  505. }
  506. else {
  507. if (albumEnable == PREMISSIONTYPE_NO) {
  508. [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
  509. }
  510. }
  511. }
  512. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getVersion"]) {
  513. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  514. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  515. [parm setValue:@"getVersion" forKey:@"api"];
  516. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  517. [content setValue:[USER_MANAGER getCurrentVersion] forKey:@"version"];
  518. [content setValue:[valueDic ks_stringValueForKey:@"uuid"] forKey:@"uuid"];
  519. [sendParm setValue:content forKey:@"content"];
  520. [self postMessage:sendParm];
  521. }
  522. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getDeviceStatus"]) {
  523. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  524. NSString *type = [valueDic ks_stringValueForKey:@"type"];
  525. if ([type isEqualToString:@"video"]) {
  526. NSString *status = [UIScreen mainScreen].isCaptured ? @"1" : @"0";
  527. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  528. [sendParm setValue:@"getDeviceStatus" forKey:@"api"];
  529. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  530. [content setValue:[valueDic ks_stringValueForKey:@"type"] forKey:@"type"];
  531. [content setValue:[valueDic ks_stringValueForKey:@"uuid"] forKey:@"uuid"];
  532. [content setValue:status forKey:@"status"];
  533. [sendParm setValue:content forKey:@"content"];
  534. [self postMessage:sendParm];
  535. if ([status isEqualToString:@"1"]) {
  536. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"为了保证数据安全,请不要录屏"];
  537. }
  538. }
  539. }
  540. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setEventTracking"]) {
  541. NSString *type = [[parm ks_dictionaryValueForKey:@"content"] ks_stringValueForKey:@"type"];
  542. [USER_MANAGER sendUMEvent:type];
  543. }
  544. }
  545. - (void)chooseFileWithType:(NSString *)typeStr maxNumber:(NSInteger)maxCount bucket:(NSString *)bucket {
  546. if ([typeStr isEqualToString:@"img"]) { // 选择图片上传
  547. if (maxCount > 9) {
  548. maxCount = 9;
  549. }
  550. [self chooseMediaWithType:MEDIATYPE_PHOTO maxCount:maxCount bucket:bucket];
  551. }
  552. else if ([typeStr isEqualToString:@"video"]) {
  553. [self chooseMediaWithType:MEDIATYPE_VIDEO maxCount:1 bucket:bucket];
  554. }
  555. else if ([typeStr isEqualToString:@"file"]) {
  556. [self chooseDocumentWithType:CHOOSETYPE_ALL bucket:bucket];
  557. }
  558. else if ([typeStr isEqualToString:@"midi"]) {
  559. [self chooseDocumentWithType:CHOOSETYPE_MIDI bucket:bucket];
  560. }
  561. else if ([typeStr isEqualToString:@"mp3"]) {
  562. [self chooseDocumentWithType:CHOOSETYPE_MP3 bucket:bucket];
  563. }
  564. else if ([typeStr isEqualToString:@"xml"]) {
  565. [self chooseDocumentWithType:CHOOSETYPE_XML bucket:bucket];
  566. }
  567. }
  568. - (void)chooseDocumentWithType:(CHOOSETYPE)fileTyle bucket:(NSString *)bucket {
  569. self.bucketName = bucket;
  570. self.fileChooseType = fileTyle;
  571. NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code", @"public.image", @"public.audio", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
  572. KSDocumentViewController *documentPickerViewController = [[KSDocumentViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeImport];
  573. documentPickerViewController.delegate = self;
  574. documentPickerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  575. [self presentViewController:documentPickerViewController animated:YES completion:nil];
  576. }
  577. - (void)chooseMediaWithType:(MEDIATYPE)type maxCount:(NSInteger)maxCount bucket:(NSString *)bucketName {
  578. self.mediaManager = [[KSMediaManager alloc] init];
  579. self.mediaManager.mediaType = type;
  580. self.mediaManager.maxPhotoNumber = maxCount;
  581. self.mediaManager.baseCtrl = self;
  582. self.mediaManager.needCropImage = NO;
  583. self.mediaManager.videoMaxDuration = 40 * 60;
  584. MJWeakSelf;
  585. [self.mediaManager noAlertCallback:^(NSString * _Nullable videoUrl, NSMutableArray * _Nullable imageArray, NSMutableArray * _Nullable imageAsset) {
  586. if (type == MEDIATYPE_PHOTO) {
  587. [self uploadImageArray:imageArray bucket:bucketName];
  588. }
  589. else {
  590. NSLog(@"%@", videoUrl);
  591. // 上传视频
  592. [weakSelf uploadVideoWithUrl:videoUrl bucket:bucketName];
  593. }
  594. }];
  595. [self.mediaManager pushImagePickerController];
  596. }
  597. - (void)savePicCallback:(NSString *)uuid isSuccess:(BOOL)isSuccess {
  598. NSString *status = isSuccess ? @"success" : @"fail";
  599. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  600. [parm setValue:@"savePicture" forKey:@"api"];
  601. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  602. [content setValue:status forKey:@"status"];
  603. [content setValue:uuid forKey:@"uuid"];
  604. [parm setValue:content forKey:@"content"];
  605. [self postMessage:parm];
  606. }
  607. - (void)sendAddressAction:(AddressListModel *)model {
  608. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  609. [sendParm setValue:@"getAddress" forKey:@"api"];
  610. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  611. [content setValue:model.internalBaseClassIdentifier forKey:@"id"];
  612. [content setValue:model.detailAddress forKey:@"detailAddress"];
  613. [content setValue:model.city forKey:@"city"];
  614. [content setValue:model.region forKey:@"region"];
  615. [content setValue:model.province forKey:@"province"];
  616. [content setValue:model.name forKey:@"name"];
  617. [content setValue:model.phoneNumber forKey:@"phoneNumber"];
  618. [content setValue:model.postCode forKey:@"postCode"];
  619. [sendParm setValue:content forKey:@"content"];
  620. [self postMessage:sendParm];
  621. }
  622. - (UIImage *)imageWithBase64String:(NSString *)base64String {
  623. NSURL *URL = [NSURL URLWithString:base64String];
  624. NSData *imageData = [NSData dataWithContentsOfURL:URL];
  625. UIImage *image = [UIImage imageWithData:imageData scale:2];
  626. return image;
  627. }
  628. - (void)shareFunctionWithParm:(NSDictionary *)parm {
  629. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  630. NSString *typeString = [content ks_stringValueForKey:@"type"];
  631. KSSHARETYPE shareType = [typeString isEqualToString:@"image"] ? KSSHARETYPE_IMAGE : KSSHARETYPE_VODEO;
  632. NSString *shareTitle = [content ks_stringValueForKey:@"title"];
  633. NSString *descMessage = [content ks_stringValueForKey:@"desc"];
  634. NSString *videoUrl = [content ks_stringValueForKey:@"video"];
  635. NSString *saveLinkUrl = [content ks_stringValueForKey:@"url"];
  636. NSString *imgStr = [content ks_stringValueForKey:@"image"];
  637. UIImage *shareImage = [self imageWithBase64String:imgStr];
  638. NSArray *buttonArray = [content ks_arrayValueForKey:@"button"];
  639. BOOL containCopyButton = NO;
  640. for (NSString *nameString in buttonArray) {
  641. if ([nameString isEqualToString:@"copy"]) {
  642. containCopyButton = YES;
  643. break;
  644. }
  645. }
  646. [KSUMShareManager shareInstanceShowWithImage:shareImage showSaveLink:containCopyButton saveLinkUrl:saveLinkUrl url:videoUrl shareTitle:shareTitle descMessage:descMessage shareType:shareType showInView:self callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
  647. NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  648. [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
  649. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  650. [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
  651. [content setValue:descMessage forKey:@"message"];
  652. BOOL status = isSuccess;
  653. [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  654. [responParm setValue:content forKey:@"content"];
  655. [self postMessage:responParm];
  656. }];
  657. }
  658. - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
  659. [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
  660. } confirm:^{
  661. [self openSettingView];
  662. }];
  663. }
  664. - (void)openSettingView {
  665. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
  666. }
  667. - (void)displaySource:(NSURL *)localUrl {
  668. KSLocalWebViewController *ctrl = [[KSLocalWebViewController alloc] init];
  669. ctrl.headTitle = @"协议文件";
  670. ctrl.sourceData = [NSData dataWithContentsOfURL:localUrl];
  671. ctrl.fileUrl = localUrl;
  672. [self.navigationController pushViewController:ctrl animated:YES];
  673. }
  674. - (void)postMessage:(NSDictionary *)parm {
  675. NSLog(@"------ parm %@", [parm mj_JSONString]);
  676. if (_myWebView) {
  677. dispatch_async(dispatch_get_main_queue(), ^{
  678. NSString *jsString = [parm mj_JSONString];
  679. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"postMessage(%@,'*')", jsString] completionHandler:nil];
  680. });
  681. }
  682. }
  683. // 刷新
  684. - (void)refreshUrl:(NSString *)refreshUrl {
  685. NSString *sepectString = [refreshUrl containsString:@"?"] ? @"&" : @"?";
  686. NSString *tokenStr = UserDefault(TokenKey);
  687. if (![NSString isEmptyString:tokenStr]) {
  688. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  689. refreshUrl = [NSString stringWithFormat:@"%@%@%@",refreshUrl, sepectString, token];
  690. }
  691. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:refreshUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  692. [self.myWebView loadRequest:request];
  693. }
  694. // 返回登录页面
  695. - (void)backLoginView {
  696. NSString *webUrl = [self.url copy];
  697. if ([webUrl containsString:@"Authorization="]) {
  698. NSRange range = [webUrl rangeOfString:@"Authorization="];
  699. if (range.location != NSNotFound) {
  700. webUrl = [webUrl substringToIndex:range.location-1];
  701. }
  702. }
  703. // 获取次数
  704. NSString *failCount = UserDefault(@"WEB_FAILCOUNT");
  705. if ([NSString isEmptyString:failCount]) {
  706. failCount = @"1";
  707. UserDefaultSetObjectForKey(failCount, @"WEB_FAILCOUNT");
  708. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  709. }
  710. else if (failCount.integerValue == 1) {
  711. NSString *preUrl = UserDefaultObjectForKey(FAIL_WEB_URL);
  712. if (![webUrl isEqualToString:preUrl]) { // 如果打开和之前失败不相同重新统计数据
  713. UserDefaultSetObjectForKey(@"1", @"WEB_FAILCOUNT");
  714. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  715. }
  716. else {
  717. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  718. }
  719. }
  720. else {
  721. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  722. }
  723. // 当前失败的H5地址
  724. UserDefaultSetObjectForKey(webUrl, FAIL_WEB_URL);
  725. // 退出登录
  726. [APPLOGIN_MANAGER logoutAction];
  727. }
  728. #pragma mark ----- WKWebView delegate
  729. // 1 在发送请求之前,决定是否跳转
  730. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  731. NSLog(@"1-------在发送请求之前,决定是否跳转 -->%@",navigationAction.request);
  732. NSURL *url = navigationAction.request.URL;
  733. NSString *scheme = [url scheme];
  734. UIApplication *app = [UIApplication sharedApplication];
  735. NSString *urlString = url.absoluteString;
  736. if (![urlString containsString:@"colexiu.com"] && ![urlString containsString:WEBHOST]) { // 外部链接
  737. self.isOutLink = YES;
  738. }
  739. else {
  740. self.isOutLink = NO;
  741. }
  742. // 打电话
  743. if ([scheme isEqualToString:@"tel"]) {
  744. if ([app canOpenURL:url]) {
  745. [app openURL:url];
  746. // 一定要加上这句,否则会打开新页面
  747. decisionHandler(WKNavigationActionPolicyCancel);
  748. return;
  749. }
  750. }
  751. decisionHandler(WKNavigationActionPolicyAllow);
  752. }
  753. // 2 页面开始加载时调用
  754. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  755. NSLog(@"2-------页面开始加载时调用");
  756. }
  757. // 3 在收到响应后,决定是否跳转
  758. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  759. /// 在收到服务器的响应头,根据response相关信息,决定是否跳转。decisionHandler必须调用,来决定是否跳转,参数WKNavigationActionPolicyCancel取消跳转,WKNavigationActionPolicyAllow允许跳转
  760. NSLog(@"3-------在收到响应后,决定是否跳转");
  761. decisionHandler(WKNavigationResponsePolicyAllow);
  762. }
  763. // 4 当内容开始返回时调用
  764. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
  765. NSLog(@"4-------当内容开始返回时调用");
  766. }
  767. // 5 页面加载完成之后调用
  768. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  769. NSLog(@"5-------页面加载完成之后调用");
  770. if (_hasModify == NO) {
  771. [self configLocalStorage];
  772. }
  773. }
  774. // 调用js方法
  775. - (void)postMessageJS:(NSDictionary *)jsDict {
  776. NSString *jsString = [jsDict mj_JSONString];
  777. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"sendMessage(%@)", jsString] completionHandler:nil];
  778. }
  779. // 6 页面加载失败时调用
  780. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
  781. NSLog(@"6-------页面加载失败时调用");
  782. [self showErrorView];
  783. }
  784. // 接收到服务器跳转请求之后调用
  785. - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
  786. NSLog(@"-------接收到服务器跳转请求之后调用");
  787. }
  788. // 数据加载发生错误时调用
  789. - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
  790. NSLog(@"----数据加载发生错误时调用");
  791. }
  792. - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
  793. {
  794. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  795. if (challenge.previousFailureCount == 0) {
  796. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  797. completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
  798. } else {
  799. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  800. }
  801. }
  802. }
  803. //当因为某些问题,导致webView进程终止时触发
  804. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
  805. NSLog(@"%s", __func__);
  806. [webView reload];
  807. }
  808. /**
  809. * web界面中有弹出警告框时调用
  810. *
  811. * @param webView 实现该代理的webview
  812. * @param message 警告框中的内容
  813. * @param completionHandler 警告框消失调用
  814. */
  815. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
  816. NSLog(@"-------web界面中有弹出警告框时调用");
  817. NSLog(@"%@",message);
  818. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  819. message:nil
  820. preferredStyle:UIAlertControllerStyleAlert];
  821. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  822. style:UIAlertActionStyleCancel
  823. handler:^(UIAlertAction *action) {
  824. completionHandler();
  825. }]];
  826. [self presentViewController:alertController animated:YES completion:nil];
  827. }
  828. // 取消和确认的按钮
  829. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
  830. // js 里面的alert实现,如果不实现,网页的alert函数无效 ,
  831. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  832. message:nil
  833. preferredStyle:UIAlertControllerStyleAlert];
  834. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  835. style:UIAlertActionStyleDefault
  836. handler:^(UIAlertAction *action) {
  837. completionHandler(YES);
  838. }]];
  839. [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
  840. style:UIAlertActionStyleCancel
  841. handler:^(UIAlertAction *action){
  842. completionHandler(NO);
  843. }]];
  844. [self presentViewController:alertController animated:YES completion:^{}];
  845. }
  846. #pragma mark - KVO回馈
  847. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  848. if ([keyPath isEqualToString:@"estimatedProgress"]) {
  849. self.progressLayer.opacity = 1;
  850. if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
  851. return;
  852. }
  853. self.progressLayer.frame = CGRectMake(0, 0, kScreenWidth*[change[@"new"] floatValue], 3);
  854. if ([change[@"new"]floatValue] == 1.0) {
  855. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  856. self.progressLayer.opacity = 0;
  857. self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
  858. });
  859. }
  860. }
  861. }
  862. /*
  863. #pragma mark - Navigation
  864. // In a storyboard-based application, you will often want to do a little preparation before navigation
  865. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  866. // Get the new view controller using [segue destinationViewController].
  867. // Pass the selected object to the new view controller.
  868. }
  869. */
  870. - (void)configLocalStorage {
  871. _hasModify = YES;
  872. if (![NSString isEmptyString:UserDefault(TokenKey)]) {
  873. NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('Authorization', '%@ %@')",UserDefault(Token_type), UserDefault(TokenKey)];
  874. [self.myWebView evaluateJavaScript:jsString completionHandler:nil];
  875. }
  876. }
  877. - (void)setupProgress {
  878. UIView *progress = [[UIView alloc]init];
  879. progress.frame = CGRectMake(0, 0, kScreenWidth, 3);
  880. progress.backgroundColor = [UIColor clearColor];
  881. [self.view addSubview:progress];
  882. CALayer *layer = [CALayer layer];
  883. layer.frame = CGRectMake(0, 0, 0, 3);
  884. layer.backgroundColor = CLIENT_THEMECOLOR.CGColor;
  885. [progress.layer addSublayer:layer];
  886. self.progressLayer = layer;
  887. }
  888. + (WKProcessPool*)singleWkProcessPool {
  889. static WKProcessPool *sharedPool;
  890. static dispatch_once_t onceToken;
  891. dispatch_once(&onceToken, ^{
  892. sharedPool = [[WKProcessPool alloc] init];
  893. });
  894. return sharedPool;
  895. }
  896. - (NSDictionary *)convertJsonStringToNSDictionary:(NSString *)jsonString {
  897. if (jsonString == nil) {
  898. return nil;
  899. }
  900. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  901. NSError *error;
  902. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
  903. if (error) {
  904. NSLog(@"jsonString解析失败:%@", error);
  905. return nil;
  906. }
  907. return json;
  908. }
  909. - (void)dealloc {
  910. NSLog(@"webView dealloc -----");
  911. [[_myWebView configuration].userContentController removeScriptMessageHandlerForName:@"COLEXIU"];
  912. [_myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
  913. [_myWebView loadHTMLString:@"" baseURL:nil];
  914. [_myWebView removeFromSuperview];
  915. _myWebView = nil;
  916. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  917. [[NSURLCache sharedURLCache] setDiskCapacity:0];
  918. [[NSURLCache sharedURLCache] setMemoryCapacity:0];
  919. [[NSNotificationCenter defaultCenter] removeObserver:self];
  920. }
  921. - (NSString *)getSaveSpeedPath {
  922. // 在Documents目录下创建一个名为AudioSpeedFile的文件夹
  923. NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioSpeedFile"];
  924. NSLog(@"%@",path);
  925. NSFileManager *fileManager = [NSFileManager defaultManager];
  926. BOOL isDir = FALSE;
  927. BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
  928. if(!(isDirExist && isDir)) {
  929. BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  930. if(!bCreateDir){
  931. NSLog(@"创建文件夹失败!");
  932. }
  933. NSLog(@"创建文件夹成功,文件路径%@",path);
  934. }
  935. path = [path stringByAppendingPathComponent:@"songSpeed.plist"];
  936. NSLog(@"file path:%@",path);
  937. return path;
  938. }
  939. #pragma mark -- 上传图片
  940. - (void)hudTipWillShow:(BOOL)willShow{
  941. if (willShow) {
  942. [self resignFirstResponder];
  943. UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
  944. if (!_HUD) {
  945. _HUD = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
  946. _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
  947. _HUD.label.text = @"正在上传视频...";
  948. _HUD.contentColor = [UIColor whiteColor];
  949. _HUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
  950. _HUD.bezelView.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.8];
  951. _HUD.removeFromSuperViewOnHide = YES;
  952. }else{
  953. _HUD.progress = 0;
  954. [keyWindow addSubview:_HUD];
  955. [_HUD showAnimated:YES];
  956. }
  957. }else{
  958. [_HUD hideAnimated:YES];
  959. }
  960. }
  961. - (void)uploadImageArray:(NSMutableArray *)imageArray bucket:(NSString *)bucket {
  962. [LOADING_MANAGER showHUD];
  963. NSMutableArray *imageDataArray = [NSMutableArray array];
  964. for (UIImage *image in imageArray) {
  965. NSData *imgData = [UIImage turnsImaegDataByImage:image];
  966. [imageDataArray addObject:imgData];
  967. }
  968. [[KSUploadManager shareInstance] configBucketName:bucket];
  969. [[KSUploadManager shareInstance] mutilUploadImage:imageDataArray fileName:@"complainImg" successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  970. [LOADING_MANAGER removeHUD];
  971. NSMutableArray *urlArray = [NSMutableArray array];
  972. for (NSString *url in fileUrlArray) {
  973. [urlArray addObject:url];
  974. }
  975. NSString *attachments = [urlArray componentsJoinedByString:@","];
  976. if (self.chooseFileParm) { // 回调
  977. [self.chooseFileParm setValue:attachments forKey:@"fileUrl"];
  978. [self postMessage:self.chooseFileParm];
  979. self.chooseFileParm = nil;
  980. }
  981. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  982. [LOADING_MANAGER removeHUD];
  983. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  984. [self fileChooseErrorCallback];
  985. }];
  986. }
  987. #pragma mark --- 上传视频文件
  988. - (void)uploadVideoWithUrl:(NSString *)videoUrl bucket:(NSString *)bucket {
  989. // 取出视频第一帧
  990. UIImage *previewImage = [self firstFrameWithVideoURL:[NSURL fileURLWithPath:videoUrl] size:CGSizeMake(1280, 720)];
  991. __block NSString *imageUrl = @"";
  992. if (previewImage) { // 如果有第一帧
  993. NSData *imgData = [UIImage turnsImaegDataByImage:previewImage];
  994. NSString *fileName = @"videoPreviewImg";
  995. [[KSUploadManager shareInstance] configBucketName:bucket];
  996. [[KSUploadManager shareInstance] uploadImage:imgData fileName:fileName successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  997. NSString *url = [fileUrlArray lastObject];
  998. imageUrl = url;
  999. [self submitUrlWith:imageUrl videoUrl:videoUrl];
  1000. } faliure:^(NSError * _Nullable error, NSString *descMessaeg) {
  1001. if ([NSString isEmptyString:descMessaeg]) {
  1002. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1003. }
  1004. [self fileChooseErrorCallback];
  1005. }];
  1006. }
  1007. else {
  1008. [self submitUrlWith:nil videoUrl:videoUrl];
  1009. }
  1010. }
  1011. - (void)submitUrlWith:(NSString *)imgUrl videoUrl:(NSString *)videoUrl {
  1012. // 上传视频
  1013. [self hudTipWillShow:YES];
  1014. NSURL *uploadFileUrl = [NSURL fileURLWithPath:videoUrl];
  1015. NSData *fileData = [NSData dataWithContentsOfURL:uploadFileUrl];
  1016. NSString *suffix = [NSString stringWithFormat:@".%@",[uploadFileUrl pathExtension]];
  1017. [[KSUploadManager shareInstance] videoUpload:fileData fileName:@"video" fileSuffix:suffix progress:^(int64_t bytesWritten, int64_t totalBytes) {
  1018. dispatch_main_async_safe(^{
  1019. // 显示进度
  1020. if (self.HUD) {
  1021. self.HUD.progress = bytesWritten / totalBytes;// progress是回调进度
  1022. }
  1023. });
  1024. } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1025. [self hudTipWillShow:NO];
  1026. NSString *fileUrl = [fileUrlArray lastObject];
  1027. [self videoUploadCallback:fileUrl firstFrameImg:imgUrl];
  1028. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1029. [self hudTipWillShow:NO];
  1030. if ([NSString isEmptyString:descMessaeg]) {
  1031. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1032. }
  1033. [self videoUploadCallback:@"" firstFrameImg:@""];
  1034. }];
  1035. }
  1036. - (void)videoUploadCallback:(NSString *)remoteVideoUrl firstFrameImg:(NSString *)imgUrl {
  1037. if (self.chooseFileParm) { // 回调
  1038. [self.chooseFileParm setValue:remoteVideoUrl forKey:@"fileUrl"];
  1039. [self.chooseFileParm setValue:imgUrl forKey:@"firstFrameImg"];
  1040. [self postMessage:self.chooseFileParm];
  1041. self.chooseFileParm = nil;
  1042. }
  1043. }
  1044. #pragma mark ---- 获取图片第一帧
  1045. - (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
  1046. {
  1047. // 获取视频第一帧
  1048. NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
  1049. AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
  1050. AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
  1051. generator.appliesPreferredTrackTransform = YES;
  1052. generator.maximumSize = CGSizeMake(size.width, size.height);
  1053. NSError *error = nil;
  1054. CGImageRef imgRef = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
  1055. if (imgRef) {
  1056. UIImage *image = [UIImage imageWithCGImage:imgRef];
  1057. CGImageRelease(imgRef);
  1058. return image;
  1059. }
  1060. else {
  1061. return nil;
  1062. }
  1063. }
  1064. #pragma mark ---- UIDocumentPickerDelegate
  1065. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
  1066. [self fileChooseErrorCallback];
  1067. }
  1068. - (void)fileChooseErrorCallback {
  1069. if (self.chooseFileParm) { // 回调
  1070. [self.chooseFileParm setValue:@"" forKey:@"fileUrl"];
  1071. [self postMessage:self.chooseFileParm];
  1072. self.chooseFileParm = nil;
  1073. }
  1074. }
  1075. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
  1076. NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
  1077. NSString *fileName = [array lastObject];
  1078. fileName = [fileName stringByRemovingPercentEncoding];
  1079. if (self.fileChooseType == CHOOSETYPE_XML) {
  1080. if (![fileName hasSuffix:@".xml"]) {
  1081. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传XML格式文件"];
  1082. [self fileChooseErrorCallback];
  1083. return;
  1084. }
  1085. }
  1086. else if (self.fileChooseType == CHOOSETYPE_MIDI) {
  1087. if (![fileName hasSuffix:@".mid"] || [fileName hasSuffix:@".midi"]) {
  1088. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传mid格式文件"];
  1089. [self fileChooseErrorCallback];
  1090. return;
  1091. }
  1092. }
  1093. else if (self.fileChooseType == CHOOSETYPE_MP3) {
  1094. if (![fileName hasSuffix:@".mp3"]) {
  1095. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传mp3格式文件"];
  1096. [self fileChooseErrorCallback];
  1097. return;
  1098. }
  1099. }
  1100. else {
  1101. if (![fileName hasSuffix:@".mp3"] && ![fileName hasSuffix:@".aac"]) {
  1102. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"暂不支持此格式!"];
  1103. [self fileChooseErrorCallback];
  1104. return;
  1105. }
  1106. }
  1107. __block NSString * fileUrl = @"";
  1108. if ([KSICloudManager iCloudEnable]) {
  1109. [KSICloudManager downloadWithDocumentURL:url callBack:^(id obj) {
  1110. NSData *data = obj;
  1111. //写入沙盒Documents
  1112. NSString *pathStr = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",fileName]];
  1113. [data writeToFile:pathStr atomically:YES];
  1114. if (![[NSFileManager defaultManager] fileExistsAtPath:pathStr]) {
  1115. BOOL isSuccess = [data writeToFile:pathStr atomically:YES];
  1116. if (isSuccess) {
  1117. fileUrl = pathStr;
  1118. }
  1119. else {
  1120. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"写入文件错误!"];
  1121. [self fileChooseErrorCallback];
  1122. }
  1123. }
  1124. else {
  1125. fileUrl = pathStr;
  1126. }
  1127. [self uploadFile:fileName fileUrl:pathStr];
  1128. }];
  1129. }
  1130. else {
  1131. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"iCloud不可用!"];
  1132. [self fileChooseErrorCallback];
  1133. }
  1134. }
  1135. - (void)uploadFile:(NSString *)fileName fileUrl:(NSString *)fileUrl {
  1136. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1137. [LOADING_MANAGER showHUD];
  1138. NSString *suffix = [NSString stringWithFormat:@".%@",[[fileName componentsSeparatedByString:@"."] lastObject]];
  1139. NSData *fileData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:fileUrl]];
  1140. [[KSUploadManager shareInstance] configBucketName:self.bucketName];
  1141. [[KSUploadManager shareInstance] uploadFile:fileData fileName:@"file" fileSuffix:suffix successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1142. [LOADING_MANAGER removeHUD];
  1143. NSString *fileUrl = [fileUrlArray lastObject];
  1144. if (self.chooseFileParm) { // 回调
  1145. [self.chooseFileParm setValue:fileUrl forKey:@"fileUrl"];
  1146. [self postMessage:self.chooseFileParm];
  1147. self.chooseFileParm = nil;
  1148. }
  1149. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1150. [LOADING_MANAGER removeHUD];
  1151. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1152. [self fileChooseErrorCallback];
  1153. }];
  1154. });
  1155. }
  1156. - (CGFloat)getFileSize:(NSURL *)fileUrl {
  1157. NSFileManager *fileManager = [NSFileManager defaultManager];
  1158. float filesize = -1.0;
  1159. NSString *path = fileUrl.path;
  1160. if ([fileManager fileExistsAtPath:path]) {
  1161. NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
  1162. unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
  1163. filesize = 1.0*size/1024/1024;
  1164. }
  1165. return filesize;
  1166. }
  1167. - (KSWebLoadRefreshView *)errorView {
  1168. if (!_errorView) {
  1169. _errorView = [KSWebLoadRefreshView shareInstance];
  1170. MJWeakSelf;
  1171. [_errorView failViewActionCallback:^(BOOL isBack) {
  1172. [weakSelf hideErrorView];
  1173. if (isBack) {
  1174. [weakSelf backAction];
  1175. }
  1176. else {
  1177. [weakSelf loadRequest];
  1178. }
  1179. }];
  1180. }
  1181. return _errorView;
  1182. }
  1183. - (void)showErrorView {
  1184. if (![self.view.subviews containsObject:self.errorView]) {
  1185. [self.view addSubview:self.errorView];
  1186. [self.errorView mas_makeConstraints:^(MASConstraintMaker *make) {
  1187. make.left.right.top.bottom.mas_equalTo(self.view);
  1188. }];
  1189. [self.view bringSubviewToFront:self.errorView];
  1190. }
  1191. }
  1192. - (void)hideErrorView {
  1193. if ([self.view.subviews containsObject:self.errorView]) {
  1194. [self.errorView removeFromSuperview];
  1195. }
  1196. }
  1197. /*
  1198. #pragma mark - Navigation
  1199. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1200. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1201. // Get the new view controller using [segue destinationViewController].
  1202. // Pass the selected object to the new view controller.
  1203. }
  1204. */
  1205. @end