KSBaseWKWebViewController.m 58 KB

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