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