KSBaseWKWebViewController.m 54 KB

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