KSBaseWKWebViewController.m 57 KB

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