KSBaseWKWebViewController.m 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  1. //
  2. // KSBaseWKWebViewController.m
  3. // KulexiuForTeacher
  4. //
  5. // Created by Kyle on 2022/3/17.
  6. //
  7. #import "KSBaseWKWebViewController.h"
  8. #import "WebViewBaseConfig.h" // 基础配置
  9. #import <KSToolLibrary/UIDevice+TFDevice.h> // 横竖屏
  10. // 其他web
  11. #import "KSLocalWebViewController.h"
  12. #import "KSAccompanyWebViewController.h"
  13. #import "AppDelegate+AppService.h"
  14. #import "UserInfoManager.h"
  15. #import "KSMediaManager.h"
  16. #import "KSUMShareManager.h"
  17. #import "KSOrderManager.h"
  18. #import "KSEnterLiveroomManager.h"
  19. // 保存文件
  20. #import <KSToolLibrary/KSICloudManager.h>
  21. #import <KSToolLibrary/KSDocumentViewController.h>
  22. // 聊天页面
  23. #import "KSChatConversationViewController.h"
  24. #import "KSGroupConversationController.h"
  25. #import "AddressListViewController.h"
  26. // 视频封面选择
  27. #import "KSVideoCropViewController.h"
  28. // 错误刷新web 页面
  29. #import "KSWebLoadRefreshView.h"
  30. #import "KSNewAlertView.h"
  31. #import "KSLogManager.h"
  32. typedef NS_ENUM(NSInteger, CHOOSETYPE) {
  33. CHOOSETYPE_XML,
  34. CHOOSETYPE_MIDI,
  35. CHOOSETYPE_MP3,
  36. CHOOSETYPE_ALL,
  37. };
  38. @interface KSBaseWKWebViewController ()<UIDocumentPickerDelegate,UIDocumentInteractionControllerDelegate>
  39. @property (nonatomic, assign) BOOL isOutLink; // 外部链接
  40. @property (nonatomic,weak) CALayer *progressLayer;
  41. @property (nonatomic, assign) BOOL hasModify;
  42. @property (nonatomic, assign) BOOL hasChangeSource; // 是否切换了亮屏,横屏等配置
  43. /// 选择本地文件 parm
  44. @property (nonatomic, strong) NSMutableDictionary *chooseFileParm;
  45. @property (nonatomic, strong) KSMediaManager *mediaManager;
  46. @property (strong, nonatomic) MBProgressHUD *HUD;
  47. @property (nonatomic, assign) CHOOSETYPE fileChooseType;
  48. @property (nonatomic, strong) NSString *bucketName;
  49. @property (nonatomic, assign) BOOL isFirstLoad;
  50. @property (nonatomic, strong) KSWebLoadRefreshView *errorView;
  51. @property (nonatomic, strong) KSUMShareManager *shareManager;
  52. @property (nonatomic, assign) BOOL isDownloadFile;
  53. @property (nonatomic, strong) KSNewAlertView *wifiAlert;
  54. @end
  55. @implementation KSBaseWKWebViewController
  56. - (void)viewDidLoad {
  57. [super viewDidLoad];
  58. // Do any additional setup after loading the view.
  59. self.ks_prefersNavigationBarHidden = YES; // 隐藏导航栏,其他事件额外处理
  60. [self initWebView];
  61. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(operationDealCallbackMessage:) name:DEALCALLBACKNOTICIFATION object:nil];
  62. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backLoginView) name:@"liveroomBackRefresh" object:nil];
  63. self.isFirstLoad = YES;
  64. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(captureViewTips:) name:UIScreenCapturedDidChangeNotification object:nil];
  65. }
  66. - (void)operationDealCallbackMessage:(NSNotification *)notification {
  67. NSString *status = [notification object];
  68. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  69. [sendParm setValue:@"paymentOperation" forKey:@"api"];
  70. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  71. [content setValue:status forKey:@"status"];
  72. [sendParm setValue:content forKey:@"content"];
  73. [self postMessage:sendParm];
  74. }
  75. - (void)setParmDic:(NSDictionary *)parmDic {
  76. _parmDic = parmDic;
  77. _hasChangeSource = YES;
  78. BOOL isOpenLight = [parmDic ks_boolValueForKey:@"isOpenLight"];
  79. [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
  80. // 横竖屏
  81. NSInteger orientation = [parmDic ks_integerValueForKey:@"orientation"];
  82. BOOL isLandScape = orientation == 0 ? YES : NO;
  83. self.ks_landScape = isLandScape;
  84. [self changeOrientation:isLandScape];
  85. }
  86. - (void)changeOrientation:(BOOL)isLandScape {
  87. if (isLandScape) {
  88. // 切换到横屏
  89. if (IS_IPAD) {
  90. self.zh_statusBarHidden = YES;
  91. }
  92. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  93. delegate.allowAutoRotate = YES;
  94. [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight inController:self];
  95. }
  96. else {
  97. if (IS_IPAD) {
  98. self.zh_statusBarHidden = NO;
  99. }
  100. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  101. delegate.allowAutoRotate = NO;
  102. [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait inController:self];
  103. }
  104. }
  105. - (void)viewWillAppear:(BOOL)animated {
  106. [super viewWillAppear:animated];
  107. if (_hasChangeSource) {
  108. [self setParmDic:self.parmDic];
  109. }
  110. if (self.isFirstLoad == NO) {
  111. [self sendResumeMessage];
  112. }
  113. self.isFirstLoad = NO;
  114. [self checkCaptured];
  115. }
  116. - (void)sendResumeMessage {
  117. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  118. [parm setValue:@"webViewOnResume" forKey:@"api"];
  119. [self postMessage:parm];
  120. }
  121. - (void)viewWillDisappear:(BOOL)animated {
  122. [super viewWillDisappear:animated];
  123. BOOL isBack = [self isViewPopDismiss];
  124. if (isBack) {
  125. if (self.preCtrl) {
  126. if (self.ks_landScape != self.preCtrl.ks_landScape) {
  127. [self changeOrientation:self.preCtrl.ks_landScape];
  128. }
  129. }
  130. if (![self.preCtrl isKindOfClass:[KSBaseWKWebViewController class]]) {
  131. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  132. }
  133. }
  134. else {
  135. if ([self.presentedViewController isKindOfClass:NSClassFromString(@"TZImagePickerController")] || [self.presentedViewController isKindOfClass:NSClassFromString(@"RSKImageCropViewController")] || [self.presentedViewController isKindOfClass:NSClassFromString(@"KSVideoCropViewController")]) {
  136. NSLog(@"-----");
  137. }
  138. else {
  139. KSBaseViewController *nextCtrl = [self getNextViewController];
  140. if (nextCtrl) {
  141. if (nextCtrl.ks_landScape != self.ks_landScape) {
  142. [self changeOrientation:NO];
  143. }
  144. }
  145. }
  146. }
  147. }
  148. - (void)initWebView {
  149. [self.scrollView removeFromSuperview];
  150. if (_myWebView == nil) {
  151. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  152. config.selectionGranularity = WKSelectionGranularityDynamic;
  153. config.allowsInlineMediaPlayback = YES;
  154. config.mediaTypesRequiringUserActionForPlayback = NO;
  155. config.processPool = [KSBaseWKWebViewController singleWkProcessPool];
  156. config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  157. [self configUserAgent:config];
  158. //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
  159. WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
  160. //这个类主要用来做native与JavaScript的交互管理
  161. WKUserContentController * wkUController = [[WKUserContentController alloc] init];
  162. [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:SCRIPT_NAME];
  163. config.userContentController = wkUController;
  164. WKPreferences *preferences = [WKPreferences new];
  165. // 是否支出javaScript
  166. preferences.javaScriptEnabled = YES;
  167. //不通过用户交互,是否可以打开窗口
  168. preferences.javaScriptCanOpenWindowsAutomatically = YES;
  169. config.preferences = preferences;
  170. _myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
  171. _myWebView.UIDelegate = self;
  172. _myWebView.navigationDelegate = self;
  173. _myWebView.scrollView.bounces = NO;
  174. _myWebView.scrollView.showsVerticalScrollIndicator = NO;
  175. _myWebView.scrollView.showsHorizontalScrollIndicator = NO;
  176. // _myWebView.allowsBackForwardNavigationGestures = YES;
  177. [self.view addSubview:_myWebView];
  178. #ifdef DEBUG
  179. if (@available(iOS 16.4, *)) {
  180. _myWebView.inspectable = YES;
  181. }
  182. #endif
  183. // 加载进度条和title
  184. [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  185. [_myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
  186. [self.view addSubview:_myWebView];
  187. [_myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
  188. make.left.right.mas_equalTo(self.view);
  189. make.top.mas_equalTo(self.view.mas_top);
  190. make.bottom.mas_equalTo(self.view.mas_bottom);
  191. }];
  192. _myWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  193. [self setupProgress];
  194. // 修改userAgent
  195. [self loadRequest];
  196. }
  197. else {
  198. [_myWebView reload];
  199. }
  200. }
  201. - (void)configUserAgent:(WKWebViewConfiguration *)config {
  202. NSString *oldUserAgent = config.applicationNameForUserAgent;
  203. NSString *newAgent = [NSString stringWithFormat:@"%@ %@ %@",oldUserAgent,AGENT_NAME,AGENT_DOMAIN];
  204. config.applicationNameForUserAgent = newAgent;
  205. }
  206. - (void)loadRequest {
  207. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  208. [self.myWebView loadRequest:request];
  209. }
  210. - (NSString *)url {
  211. if (_url) {
  212. if ([_url containsString:@"Authorization="]) {
  213. NSRange range = [_url rangeOfString:@"Authorization="];
  214. if (range.location != NSNotFound) {
  215. _url = [_url substringToIndex:range.location-1];
  216. }
  217. }
  218. NSString *sepectString = [_url containsString:@"?"] ? @"&" : @"?";
  219. NSString *tokenStr = UserDefault(TokenKey);
  220. if (![NSString isEmptyString:tokenStr]) {
  221. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  222. _url = [NSString stringWithFormat:@"%@%@%@",_url, sepectString, token];
  223. }
  224. }
  225. return _url;
  226. }
  227. #pragma mark --- 返回按钮的处理
  228. - (void)backPreViewAction {
  229. [self.myWebView stopLoading];
  230. if (_backRootView) {
  231. [self.navigationController popToRootViewControllerAnimated:NO];
  232. return;
  233. }
  234. else if (_isBackPreView) {
  235. [self.navigationController popViewControllerAnimated:YES];
  236. return;
  237. }
  238. else {
  239. [self.navigationController popViewControllerAnimated:YES];
  240. }
  241. }
  242. - (void)backAction {
  243. [self.myWebView stopLoading];
  244. if (_backRootView) {
  245. [self.navigationController popToRootViewControllerAnimated:NO];
  246. return;
  247. }
  248. else if (_isBackPreView) {
  249. [self.navigationController popViewControllerAnimated:YES];
  250. return;
  251. }
  252. else if ([self.myWebView canGoBack]) {
  253. [self.myWebView goBack];
  254. }
  255. else {
  256. [self.navigationController popViewControllerAnimated:YES];
  257. }
  258. }
  259. #pragma mark - WKScriptMessageHandler
  260. - (void)userContentController:(WKUserContentController *)userContentController
  261. didReceiveScriptMessage:(WKScriptMessage *)message {
  262. if ([message.name isEqualToString:SCRIPT_NAME]) {
  263. NSDictionary *parm = [self convertJsonStringToNSDictionary:message.body];
  264. // 回到主线程
  265. dispatch_async(dispatch_get_main_queue(), ^{
  266. [self handleScriptMessageSource:parm];
  267. });
  268. }
  269. }
  270. - (void)handleScriptMessageSource:(NSDictionary *)parm {
  271. if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"back"]) { // 返回
  272. [self backPreViewAction];
  273. }
  274. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"goBack"]) { // 逐级返回
  275. [self backAction];
  276. }
  277. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"login"]) {
  278. // 回到登录页面
  279. [self backLoginView];
  280. }
  281. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openWebView"]) { // 打开新页面
  282. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  283. KSBaseWKWebViewController *detailCtrl = [[KSBaseWKWebViewController alloc] init];
  284. detailCtrl.url = [valueDic ks_stringValueForKey:@"url"];
  285. detailCtrl.parmDic = valueDic;
  286. NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
  287. BOOL isLandScape = orientation == 0 ? YES : NO;
  288. detailCtrl.ks_landScape = isLandScape;
  289. [self postMessage:parm];
  290. [self.navigationController pushViewController:detailCtrl animated:YES];
  291. }
  292. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setRequestedOrientation"]) {
  293. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  294. // 横竖屏
  295. NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
  296. BOOL isLandScape = orientation == 0 ? YES : NO;
  297. self.ks_landScape = isLandScape;
  298. [self changeOrientation:isLandScape];
  299. }
  300. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"keepScreenLongLight"]) {
  301. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  302. BOOL isOpenLight = [valueDic ks_boolValueForKey:@"isOpenLight"];
  303. [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
  304. }
  305. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"downLoad"]) {
  306. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  307. if ([valueDic ks_stringValueForKey:@"PDF"]) {
  308. NSString *url = [valueDic ks_stringValueForKey:@"downloadUrl"];
  309. [KSNetworkingManager downloadFileRequestWithFileUrl:url progress:^(int64_t bytesRead, int64_t totalBytes) {
  310. } success:^(NSURL * _Nonnull fileUrl) {
  311. [LOADING_MANAGER KSShowMsg:@"下载成功" promptCompletion:^{
  312. [self displaySource:fileUrl];
  313. }];
  314. } faliure:^(NSError * _Nonnull error) {
  315. }];
  316. }
  317. }
  318. // 回调是否刘海屏
  319. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"isSpecialShapedScreen"]) {
  320. BOOL isShapedScreen = iPhoneXSafeTopMargin > 0 ? YES : NO;
  321. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  322. [valueDic setValue:@(isShapedScreen) forKey:@"isSpecialShapedScreen"];
  323. [valueDic setValue:@(iPhoneXSafeTopMargin*2) forKey:@"notchHeight"];
  324. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  325. [sendParm setValue:valueDic forKey:@"content"];
  326. [self postMessage:sendParm];
  327. }
  328. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getToken"]) {
  329. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  330. [valueDic setValue:UserDefault(Token_type) forKey:@"tokenType"];
  331. [valueDic setValue:UserDefault(TokenKey) forKey:@"accessToken"];
  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:@"openAccompanyWebView"]) { // 打开伴奏
  337. [RecordCheckManager checkCameraPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
  338. [self afterCheckCameraCheckMic:type parm:parm];
  339. }];
  340. }
  341. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"checkAlbum"]) { // 判断权限
  342. [RecordCheckManager checkPhotoLibraryPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
  343. if (type == PREMISSIONTYPE_YES) {
  344. [self postMessage:parm];
  345. }
  346. else {
  347. [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
  348. }
  349. }];
  350. }
  351. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"shareAchievements"]) { // 分享
  352. //
  353. [self shareFunctionWithParm:parm];
  354. }
  355. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setStatusBarTextColor"]) { // 设置状态栏颜色
  356. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  357. BOOL whiteColor = [valueDic ks_boolValueForKey:@"statusBarTextColor"];
  358. if (whiteColor) {
  359. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  360. }
  361. else {
  362. if (@available(iOS 13.0, *)) {
  363. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
  364. } else {
  365. // Fallback on earlier versions
  366. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
  367. }
  368. }
  369. }
  370. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getNavHeight"]) { // 获取状态栏高度和 title heigt
  371. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  372. [valueDic setValue:[NSNumber numberWithFloat:STATUS_GAP*2] forKey:@"navHeight"];
  373. [valueDic setValue:@(44*2) forKey:@"titleHeight"];
  374. [parm setValue:valueDic forKey:@"content"];
  375. [self postMessage:parm];
  376. }
  377. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"joinChatGroup"]) {
  378. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  379. NSString *targetId = [valueDic ks_stringValueForKey:@"id"];
  380. if ([[valueDic ks_stringValueForKey:@"type"] isEqualToString:@"single"]) { // 单聊
  381. TUIChatConversationModel *model = [[TUIChatConversationModel alloc] init];
  382. model.userID = targetId;
  383. KSChatConversationViewController *ctrl = [[KSChatConversationViewController alloc] init];
  384. ctrl.conversation = model;
  385. [self.navigationController pushViewController:ctrl animated:YES];
  386. }
  387. else if ([[valueDic ks_stringValueForKey:@"type"] isEqualToString:@"multi"]) { // 群聊
  388. if ([NSString isEmptyString:targetId]) {
  389. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"报名未结束,暂无群组"];
  390. return;
  391. }
  392. TUIChatConversationModel *model = [[TUIChatConversationModel alloc] init];
  393. model.groupID = targetId;
  394. KSGroupConversationController *ctrl = [[KSGroupConversationController alloc] init];
  395. ctrl.conversation = model;
  396. [self.navigationController pushViewController:ctrl animated:YES];
  397. }
  398. }
  399. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"chooseFile"]) {
  400. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  401. self.chooseFileParm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
  402. NSString *typeStr = [valueDic ks_stringValueForKey:@"type"];
  403. NSInteger maxCount = [valueDic ks_integerValueForKey:@"max"];
  404. NSString *bucket = [valueDic ks_stringValueForKey:@"bucket"];
  405. [self chooseFileWithType:typeStr maxNumber:maxCount bucket:bucket];
  406. }
  407. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setAddress"]) { // 跳转地址选择
  408. AddressListViewController *ctrl = [[AddressListViewController alloc] init];
  409. ctrl.isChooseAddress = YES;
  410. MJWeakSelf;
  411. [ctrl chooseAddressAction:^(AddressListModel * _Nonnull model) {
  412. [weakSelf sendAddressAction:model];
  413. }];
  414. [self.navigationController pushViewController:ctrl animated:YES];
  415. }
  416. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"savePicture"]) { // 保存图片到相册
  417. // 判断相册权限
  418. [RecordCheckManager checkPhotoLibraryPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
  419. if (type == PREMISSIONTYPE_YES) {
  420. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  421. NSString *base64String = [valueDic ks_stringValueForKey:@"base64"];
  422. UIImage *saveImage = [self imageWithBase64String:base64String];
  423. [[TZImageManager manager] savePhotoWithImage:saveImage completion:^(PHAsset *asset, NSError *error) {
  424. if (!error) {
  425. [self savePicCallback:[valueDic ks_stringValueForKey:@"uuid"] isSuccess:YES];
  426. }
  427. else {
  428. [self savePicCallback:[valueDic ks_stringValueForKey:@"uuid"] isSuccess:NO];
  429. }
  430. }];
  431. }
  432. else {
  433. [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
  434. }
  435. }];
  436. }
  437. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getVersion"]) {
  438. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  439. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  440. [parm setValue:@"getVersion" forKey:@"api"];
  441. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  442. [content setValue:[USER_MANAGER getCurrentVersion] forKey:@"version"];
  443. [content setValue:[valueDic ks_stringValueForKey:@"uuid"] forKey:@"uuid"];
  444. [sendParm setValue:content forKey:@"content"];
  445. [self postMessage:sendParm];
  446. }
  447. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getDeviceStatus"]) {
  448. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  449. NSString *type = [valueDic ks_stringValueForKey:@"type"];
  450. if ([type isEqualToString:@"video"]) {
  451. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  452. NSString *status;
  453. if ([self checkIsCaptured]) {
  454. status = @"1";
  455. }
  456. else {
  457. status = @"0";
  458. }
  459. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  460. [sendParm setValue:@"getDeviceStatus" forKey:@"api"];
  461. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  462. [content setValue:[valueDic ks_stringValueForKey:@"type"] forKey:@"type"];
  463. [content setValue:[valueDic ks_stringValueForKey:@"uuid"] forKey:@"uuid"];
  464. [content setValue:status forKey:@"status"];
  465. [sendParm setValue:content forKey:@"content"];
  466. [self postMessage:sendParm];
  467. });
  468. }
  469. }
  470. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"callPhone"]) {
  471. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  472. NSString *phone = [valueDic ks_stringValueForKey:@"phone"];
  473. [self CallPhoneWith:phone];
  474. }
  475. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setCache"]) {
  476. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  477. NSString *key = [valueDic ks_stringValueForKey:@"key"];
  478. NSString *value = [valueDic ks_stringValueForKey:@"value"];
  479. UserDefaultSetObjectForKey(value, key);
  480. }
  481. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getCache"]) {
  482. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  483. NSString *key = [valueDic ks_stringValueForKey:@"key"];
  484. NSString *value = UserDefault(key);
  485. NSMutableDictionary *parm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
  486. [parm setValue:value forKey:@"value"];
  487. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  488. [sendParm setValue:@"getCache" forKey:@"api"];
  489. [sendParm setValue:parm forKey:@"content"];
  490. [self postMessage:sendParm];
  491. }
  492. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"isInstall"]) {
  493. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  494. NSString *type = [valueDic ks_stringValueForKey:@"type"];
  495. NSURL *url = [NSURL URLWithString:type];
  496. BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
  497. NSInteger installStatus = canOpen ? 1 : 0;
  498. NSMutableDictionary *parm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
  499. [parm setValue:@(installStatus) forKey:@"installStatus"];
  500. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  501. [sendParm setValue:@"isInstall" forKey:@"api"];
  502. [sendParm setValue:parm forKey:@"content"];
  503. [self postMessage:sendParm];
  504. }
  505. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openApp"]) {
  506. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  507. NSString *type = [valueDic ks_stringValueForKey:@"type"];
  508. NSURL *url = [NSURL URLWithString:type];
  509. if ([[UIApplication sharedApplication] canOpenURL:url]) {
  510. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  511. }
  512. }
  513. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"downloadApp"]) {
  514. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  515. NSString *openUrl = [valueDic ks_stringValueForKey:@"url"];
  516. bool can = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:openUrl]];
  517. if(can){
  518. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:nil];
  519. }
  520. }
  521. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"shareTripartite"]) { // 分享到微信
  522. [self shareToWeChat:parm];
  523. }
  524. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"saveFile"]) { // 下载资源
  525. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  526. NSString *url = [content ks_stringValueForKey:@"url"];
  527. [self downFile:url];
  528. }
  529. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"videoCrop"]) { // 选择封面
  530. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  531. KSVideoCropViewController *ctrl = [[KSVideoCropViewController alloc] init];
  532. NSString *videoUrl = [content ks_stringValueForKey:@"url"];
  533. [ctrl configWithVideoRemoteUrl:videoUrl];
  534. [ctrl changeLandScape];
  535. MJWeakSelf;
  536. [ctrl chooseCropImageCallback:^(UIImage * _Nonnull cropImage) {
  537. [weakSelf videCropImage:cropImage content:content];
  538. }];
  539. ctrl.modalPresentationStyle = UIModalPresentationFullScreen;
  540. [self.navigationController presentViewController:ctrl animated:YES completion:nil];
  541. }
  542. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"paymentOrder"]) {
  543. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  544. NSString *channel = [content ks_stringValueForKey:@"payChannel"];
  545. if ([channel isEqualToString:@"ali_app"]) {
  546. NSString *infoMessage = [content ks_stringValueForKey:@"payInfo"];
  547. [KSOrderManager dealWithAliSDK:infoMessage];
  548. }
  549. else if ([channel isEqualToString:@"wx_app"]) {
  550. NSString *infoMessage = [content ks_stringValueForKey:@"payInfo"];
  551. [KSOrderManager dealWithWXSDK:infoMessage];
  552. }
  553. }
  554. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"joinLiveRoom"]) { // 进入直播间
  555. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  556. NSString *roomId = [valueDic ks_stringValueForKey:@"roomId"];
  557. [LOADING_MANAGER showHUD];
  558. [KSEnterLiveroomManager joinLiveWithRoomId:roomId inController:(CustomNavViewController *)self.navigationController callback:^{
  559. [LOADING_MANAGER removeHUD];
  560. }];
  561. }
  562. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setEventTracking"]) {
  563. NSString *type = [[parm ks_dictionaryValueForKey:@"content"] ks_stringValueForKey:@"type"];
  564. [USER_MANAGER sendUMEvent:type];
  565. }
  566. // 课件相关
  567. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getCourseFilePath"]) { // 课件资源查询
  568. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  569. NSString *localPath = [COURSEWARE_MANAGER queryFileUrlWithParm:valueDic];
  570. BOOL isServiceStart = [AppDelegate shareAppDelegate].httpServer.isRunning;
  571. if (![NSString isEmptyString:localPath] && isServiceStart) {
  572. localPath = [[localPath componentsSeparatedByString:@"CoursewarePath/"] lastObject];
  573. localPath = [NSString stringWithFormat:@"%@%@/%@",@"http://localhost:",[AppDelegate shareAppDelegate].serverPort,localPath];
  574. NSMutableDictionary *contentParm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
  575. [contentParm setValue:localPath forKey:@"localPath"];
  576. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  577. [sendParm setValue:@"getCourseFilePath" forKey:@"api"];
  578. [sendParm setValue:contentParm forKey:@"content"];
  579. [self postMessage:sendParm];
  580. }
  581. else {
  582. [self postMessage:parm];
  583. }
  584. }
  585. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"checkCoursewareCache"]) {
  586. MJWeakSelf;
  587. [COURSEWARE_MANAGER checkCourseCacheStatus:parm callback:^(NSDictionary * _Nonnull parm) {
  588. [weakSelf postMessage:parm];
  589. }];
  590. }
  591. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"downloadCoursewareToCache"]) {
  592. NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
  593. NSString *lessonCoursewareDetailId = [[valueDic ks_dictionaryValueForKey:@"data"] ks_stringValueForKey:@"lessonCoursewareDetailId"];
  594. if (COURSEWARE_MANAGER.isDownloading) {
  595. if ([lessonCoursewareDetailId isEqualToString:COURSEWARE_MANAGER.lessonCoursewareDetailId]) {
  596. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"当前已有课件资源下载中"];
  597. [self downloadWithParm:parm];
  598. }
  599. else {
  600. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"当前已有课件资源下载中"];
  601. NSMutableDictionary *contentParm = [NSMutableDictionary dictionary];
  602. [contentParm setValue:@(3) forKey:@"status"];
  603. [contentParm setValue:@(0) forKey:@"progress"];
  604. [contentParm setValue:lessonCoursewareDetailId forKey:@"lessonCoursewareDetailId"];
  605. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  606. [sendParm setValue:@"downloadCoursewareToCache" forKey:@"api"];
  607. [sendParm setValue:contentParm forKey:@"content"];
  608. [self postMessage:sendParm];
  609. }
  610. }
  611. else {
  612. if ([self isWiFiEnable] == NO) {
  613. self.wifiAlert = [KSNewAlertView shareInstance];
  614. MJWeakSelf;
  615. [self.wifiAlert configTitle:@"提示" descMessage:@"当前非Wi-Fi环境,是否开始下载?" leftButtonTitle:@"取消" rightButtonTitle:@"确认" leftButtonAction:^{
  616. } rightButtonAction:^{
  617. [weakSelf downloadWithParm:parm];
  618. }];
  619. [self.wifiAlert showAlert];
  620. }
  621. else {
  622. [self downloadWithParm:parm];
  623. }
  624. }
  625. }
  626. else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cancelDownloadCourseware"]) { // 取消下载课件
  627. if (COURSEWARE_MANAGER.isDownloading) { // 如果在下载 取消
  628. [COURSEWARE_MANAGER cancleDownloadCourseware];
  629. }
  630. NSMutableDictionary *content = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  631. [content setValue:@(YES) forKey:@"status"];
  632. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  633. [sendParm setValue:@"cancelDownloadCourseware" forKey:@"api"];
  634. [sendParm setValue:content forKey:@"content"];
  635. [self postMessage:sendParm];
  636. }
  637. }
  638. - (void)afterCheckCameraCheckMic:(PREMISSIONTYPE)cameraType parm:(NSDictionary *)sourceParm {
  639. [RecordCheckManager checkMicPermissionAvaiableCallback:^(PREMISSIONTYPE type) {
  640. if (type == PREMISSIONTYPE_YES && cameraType == PREMISSIONTYPE_YES) {
  641. NSDictionary *valueDic = [sourceParm ks_dictionaryValueForKey:@"content"];
  642. KSAccompanyWebViewController *detailCtrl = [[KSAccompanyWebViewController alloc] init];
  643. detailCtrl.url = [valueDic ks_stringValueForKey:@"url"];
  644. detailCtrl.parmDic = valueDic;
  645. NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
  646. BOOL isLandScape = orientation == 0 ? YES : NO;
  647. detailCtrl.ks_landScape = isLandScape;
  648. [self postMessage:sourceParm];
  649. [self.navigationController pushViewController:detailCtrl animated:YES];
  650. }
  651. else { //
  652. NSString *content = @"";
  653. CHECKDEVICETYPE checkType = CHECKDEVICETYPE_BOTH;
  654. if (cameraType == PREMISSIONTYPE_NO && type == PREMISSIONTYPE_NO) {
  655. content = @"请开启相机和麦克风访问权限";
  656. checkType = CHECKDEVICETYPE_BOTH;
  657. }
  658. else if (cameraType == PREMISSIONTYPE_NO && type == PREMISSIONTYPE_YES) {
  659. content = @"请开启相机访问权限";
  660. checkType = CHECKDEVICETYPE_CAMREA;
  661. }
  662. else if (cameraType == PREMISSIONTYPE_YES && type == PREMISSIONTYPE_NO) {
  663. content = @"请开启麦克风访问权限";
  664. checkType = CHECKDEVICETYPE_MIC;
  665. }
  666. [self showAlertWithMessage:content type:checkType];
  667. }
  668. }];
  669. }
  670. - (void)downloadWithParm:(NSDictionary *)parm {
  671. MJWeakSelf;
  672. [COURSEWARE_MANAGER downloadCourseWithParm:parm callback:^(NSDictionary * _Nonnull sendParm) {
  673. [weakSelf postMessage:sendParm];
  674. }];
  675. }
  676. - (void)videCropImage:(UIImage *)cover content:(NSDictionary *)content {
  677. NSData *imgData = [UIImage turnsImaegDataByImage:cover];
  678. NSString *fileName = @"videoCoverImage";
  679. [LOADING_MANAGER showCustomLoading:@"上传中..."];
  680. [UPLOAD_MANAGER configWithfilePath:@"/user/"];
  681. [UPLOAD_MANAGER uploadFile:imgData fileName:fileName fileSuffix:[UIImage typeForImageData:imgData] progress:^(int64_t bytesWritten, int64_t totalBytes) {
  682. // 显示进度
  683. int progress = (int)(bytesWritten / totalBytes * 100);
  684. __block NSString *tipsMessage = [NSString stringWithFormat:@"上传中 %d%%",progress];
  685. dispatch_main_async_safe(^{
  686. [LOADING_MANAGER.loadingView setDisplayText:tipsMessage];
  687. });
  688. } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  689. [LOADING_MANAGER removeCustomLoading];
  690. NSString *fileUrl = [fileUrlArray lastObject];
  691. NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:content];
  692. [dic setValue:fileUrl forKey:@"videoCover"];
  693. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  694. [sendParm setValue:@"videoCrop" forKey:@"api"];
  695. [sendParm setValue:dic forKey:@"content"];
  696. [self postMessage:sendParm];
  697. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  698. [LOADING_MANAGER removeCustomLoading];
  699. }];
  700. }
  701. - (void)downFile:(NSString *)fileUrl {
  702. [LOADING_MANAGER showCustomLoading:@"文件下载中..."];
  703. [KSNetworkingManager downloadFileRequestWithFileUrl:fileUrl progress:^(int64_t bytesRead, int64_t totalBytes) {
  704. } success:^(NSURL * _Nonnull fileUrl) {
  705. [LOADING_MANAGER removeCustomLoading];
  706. [self saveFileWithUrl:fileUrl];
  707. } faliure:^(NSError * _Nonnull error) {
  708. [LOADING_MANAGER removeCustomLoading];
  709. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"下载失败"];
  710. }];
  711. }
  712. - (void)saveFileWithUrl:(NSURL *)fileUrl {
  713. if ([fileUrl.absoluteString hasSuffix:@".mp4"]) { // 视频
  714. [LOADING_MANAGER showCustomLoading:@"视频保存中..."];
  715. [[TZImageManager manager] saveVideoWithUrl:fileUrl completion:^(PHAsset *asset, NSError *error) {
  716. if (!error) {
  717. dispatch_main_async_safe(^{
  718. [LOADING_MANAGER removeCustomLoading];
  719. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"已保存到相册"];
  720. });
  721. }
  722. else {
  723. dispatch_main_async_safe(^{
  724. [LOADING_MANAGER removeCustomLoading];
  725. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"保存视频错误"];
  726. });
  727. }
  728. }];
  729. }
  730. else { // 音频
  731. [self saveFileToPhone:fileUrl];
  732. }
  733. }
  734. - (void)saveFileToPhone:(NSURL *)fileUrl {
  735. self.isDownloadFile = YES;
  736. UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithURL:fileUrl inMode:UIDocumentPickerModeExportToService];
  737. documentPicker.delegate = self;
  738. documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
  739. [self presentViewController:documentPicker animated:YES completion:nil];
  740. }
  741. - (void)chooseFileWithType:(NSString *)typeStr maxNumber:(NSInteger)maxCount bucket:(NSString *)bucket {
  742. if ([typeStr isEqualToString:@"img"]) { // 选择图片上传
  743. if (maxCount > 9) {
  744. maxCount = 9;
  745. }
  746. [self chooseMediaWithType:MEDIATYPE_PHOTO maxCount:maxCount bucket:bucket];
  747. }
  748. else if ([typeStr isEqualToString:@"video"]) {
  749. [self chooseMediaWithType:MEDIATYPE_VIDEO maxCount:1 bucket:bucket];
  750. }
  751. else if ([typeStr isEqualToString:@"file"]) {
  752. [self chooseDocumentWithType:CHOOSETYPE_ALL bucket:bucket];
  753. }
  754. else if ([typeStr isEqualToString:@"midi"]) {
  755. [self chooseDocumentWithType:CHOOSETYPE_MIDI bucket:bucket];
  756. }
  757. else if ([typeStr isEqualToString:@"mp3"]) {
  758. [self chooseDocumentWithType:CHOOSETYPE_MP3 bucket:bucket];
  759. }
  760. else if (([typeStr isEqualToString:@"xml"] || [typeStr isEqualToString:@"musicxml"])) {
  761. [self chooseDocumentWithType:CHOOSETYPE_XML bucket:bucket];
  762. }
  763. }
  764. - (void)chooseDocumentWithType:(CHOOSETYPE)fileTyle bucket:(NSString *)bucket {
  765. self.bucketName = bucket;
  766. self.fileChooseType = fileTyle;
  767. 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"];
  768. KSDocumentViewController *documentPickerViewController = [[KSDocumentViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeImport];
  769. documentPickerViewController.delegate = self;
  770. documentPickerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  771. [self presentViewController:documentPickerViewController animated:YES completion:nil];
  772. }
  773. - (void)chooseMediaWithType:(MEDIATYPE)type maxCount:(NSInteger)maxCount bucket:(NSString *)bucketName {
  774. self.mediaManager = [[KSMediaManager alloc] init];
  775. self.mediaManager.mediaType = type;
  776. self.mediaManager.maxPhotoNumber = maxCount;
  777. self.mediaManager.baseCtrl = self;
  778. self.mediaManager.needCropImage = NO;
  779. self.mediaManager.videoMaxDuration = 40 * 60;
  780. MJWeakSelf;
  781. [self.mediaManager noAlertCallback:^(NSString * _Nullable videoUrl, NSMutableArray * _Nullable imageArray, NSMutableArray * _Nullable imageAsset) {
  782. if (type == MEDIATYPE_PHOTO) {
  783. [weakSelf uploadImageArray:imageArray bucket:bucketName];
  784. }
  785. else {
  786. NSLog(@"%@", videoUrl);
  787. // 上传视频
  788. [weakSelf uploadVideoWithUrl:videoUrl bucket:bucketName];
  789. }
  790. }];
  791. [self.mediaManager pushImagePickerController];
  792. }
  793. - (void)savePicCallback:(NSString *)uuid isSuccess:(BOOL)isSuccess {
  794. NSString *status = isSuccess ? @"success" : @"fail";
  795. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  796. [parm setValue:@"savePicture" forKey:@"api"];
  797. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  798. [content setValue:status forKey:@"status"];
  799. [content setValue:uuid forKey:@"uuid"];
  800. [parm setValue:content forKey:@"content"];
  801. [self postMessage:parm];
  802. }
  803. - (void)sendAddressAction:(AddressListModel *)model {
  804. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  805. [sendParm setValue:@"getAddress" forKey:@"api"];
  806. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  807. [content setValue:model.internalBaseClassIdentifier forKey:@"id"];
  808. [content setValue:model.detailAddress forKey:@"detailAddress"];
  809. [content setValue:model.city forKey:@"city"];
  810. [content setValue:model.region forKey:@"region"];
  811. [content setValue:model.province forKey:@"province"];
  812. [content setValue:model.name forKey:@"name"];
  813. [content setValue:model.phoneNumber forKey:@"phoneNumber"];
  814. [content setValue:model.postCode forKey:@"postCode"];
  815. [sendParm setValue:content forKey:@"content"];
  816. [self postMessage:sendParm];
  817. }
  818. - (UIImage *)imageWithBase64String:(NSString *)base64String {
  819. NSURL *URL = [NSURL URLWithString:base64String];
  820. NSData *imageData = [NSData dataWithContentsOfURL:URL];
  821. UIImage *image = [UIImage imageWithData:imageData scale:2];
  822. return image;
  823. }
  824. - (void)shareFunctionWithParm:(NSDictionary *)parm {
  825. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  826. NSString *typeString = [content ks_stringValueForKey:@"type"];
  827. KSSHARETYPE shareType = [typeString isEqualToString:@"image"] ? KSSHARETYPE_IMAGE : KSSHARETYPE_VODEO;
  828. NSString *shareTitle = [content ks_stringValueForKey:@"title"];
  829. NSString *descMessage = [content ks_stringValueForKey:@"desc"];
  830. NSString *videoUrl = [content ks_stringValueForKey:@"video"];
  831. NSString *saveLinkUrl = [content ks_stringValueForKey:@"url"];
  832. NSString *imgStr = [content ks_stringValueForKey:@"image"];
  833. UIImage *shareImage = [self imageWithBase64String:imgStr];
  834. NSArray *buttonArray = [content ks_arrayValueForKey:@"button"];
  835. BOOL containCopyButton = NO;
  836. for (NSString *nameString in buttonArray) {
  837. if ([nameString isEqualToString:@"copy"]) {
  838. containCopyButton = YES;
  839. break;
  840. }
  841. }
  842. MJWeakSelf;
  843. self.shareManager = [KSUMShareManager shareInstanceShowWithImage:shareImage showSaveLink:containCopyButton saveLinkUrl:saveLinkUrl url:videoUrl shareTitle:shareTitle descMessage:descMessage shareType:shareType showInView:self callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
  844. NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  845. [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
  846. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  847. [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
  848. [content setValue:descMessage forKey:@"message"];
  849. BOOL status = isSuccess;
  850. [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  851. [responParm setValue:content forKey:@"content"];
  852. [weakSelf postMessage:responParm];
  853. }];
  854. }
  855. - (KSSHARETYPE)getTypeWithTypeString:(NSString *)typeString {
  856. if ([typeString isEqualToString:@"image"]) { // 图片
  857. return KSSHARETYPE_IMAGE;
  858. }
  859. else if ([typeString isEqualToString:@"link"]) { // 链接
  860. return KSSHARETYPE_URL;
  861. }
  862. else {
  863. return KSSHARETYPE_VODEO;
  864. }
  865. }
  866. - (void)shareToWeChat:(NSDictionary *)parm {
  867. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  868. if ([[content ks_stringValueForKey:@"shareType"] isEqualToString:@"wechat"]) {
  869. NSString *typeString = [content ks_stringValueForKey:@"type"];
  870. KSSHARETYPE shareType = [self getTypeWithTypeString:typeString];
  871. NSString *shareTitle = [content ks_stringValueForKey:@"title"];
  872. NSString *descMessage = [content ks_stringValueForKey:@"desc"];
  873. NSString *url = [content ks_stringValueForKey:@"video"];
  874. if (shareType == KSSHARETYPE_URL) {
  875. url = [content ks_stringValueForKey:@"url"];
  876. }
  877. NSString *imgStr = [content ks_stringValueForKey:@"image"];
  878. UIImage *shareImage = [self imageWithBase64String:imgStr];
  879. NSString *thumImage = [content ks_stringValueForKey:@"thumb"];
  880. MJWeakSelf;
  881. self.shareManager = [KSUMShareManager shareInstanceToWechatWithImage:shareImage url:url shareTitle:shareTitle descMessage:descMessage shareType:shareType thumImage:thumImage callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
  882. NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  883. [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
  884. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  885. [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
  886. [content setValue:descMessage forKey:@"message"];
  887. BOOL status = isSuccess;
  888. [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  889. [responParm setValue:content forKey:@"content"];
  890. [weakSelf postMessage:responParm];
  891. }];
  892. }
  893. else if ([[content ks_stringValueForKey:@"shareType"] isEqualToString:@"wechat_circle"]) { // 微信朋友圈
  894. NSString *typeString = [content ks_stringValueForKey:@"type"];
  895. KSSHARETYPE shareType = [self getTypeWithTypeString:typeString];
  896. NSString *shareTitle = [content ks_stringValueForKey:@"title"];
  897. NSString *descMessage = [content ks_stringValueForKey:@"desc"];
  898. NSString *url = [content ks_stringValueForKey:@"video"];
  899. if (shareType == KSSHARETYPE_URL) {
  900. url = [content ks_stringValueForKey:@"url"];
  901. }
  902. NSString *imgStr = [content ks_stringValueForKey:@"image"];
  903. UIImage *shareImage = [self imageWithBase64String:imgStr];
  904. NSString *thumImage = [content ks_stringValueForKey:@"thumb"];
  905. MJWeakSelf;
  906. self.shareManager = [KSUMShareManager shareInstanceToWechatCircleWithImage:shareImage url:url shareTitle:shareTitle descMessage:descMessage shareType:shareType thumImage:thumImage callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
  907. NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  908. [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
  909. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  910. [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
  911. [content setValue:descMessage forKey:@"message"];
  912. BOOL status = isSuccess;
  913. [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  914. [responParm setValue:content forKey:@"content"];
  915. [weakSelf postMessage:responParm];
  916. }];
  917. }
  918. }
  919. - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
  920. [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
  921. } confirm:^{
  922. [self openSettingView];
  923. }];
  924. }
  925. - (void)openSettingView {
  926. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
  927. }
  928. - (void)displaySource:(NSURL *)localUrl {
  929. KSLocalWebViewController *ctrl = [[KSLocalWebViewController alloc] init];
  930. ctrl.headTitle = @"协议文件";
  931. ctrl.sourceData = [NSData dataWithContentsOfURL:localUrl];
  932. ctrl.fileUrl = localUrl;
  933. [self.navigationController pushViewController:ctrl animated:YES];
  934. }
  935. - (void)postMessage:(NSDictionary *)parm {
  936. NSLog(@"------ parm %@", [parm mj_JSONString]);
  937. if (_myWebView) {
  938. dispatch_async(dispatch_get_main_queue(), ^{
  939. NSString *jsString = [parm mj_JSONString];
  940. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"postMessage(%@,'*')", jsString] completionHandler:nil];
  941. });
  942. }
  943. }
  944. // 刷新
  945. - (void)refreshUrl:(NSString *)refreshUrl {
  946. NSString *sepectString = [refreshUrl containsString:@"?"] ? @"&" : @"?";
  947. NSString *tokenStr = UserDefault(TokenKey);
  948. if (![NSString isEmptyString:tokenStr]) {
  949. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  950. refreshUrl = [NSString stringWithFormat:@"%@%@%@",refreshUrl, sepectString, token];
  951. }
  952. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:refreshUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  953. [self.myWebView loadRequest:request];
  954. }
  955. // 返回登录页面
  956. - (void)backLoginView {
  957. NSString *webUrl = [self.url copy];
  958. if ([webUrl containsString:@"Authorization="]) {
  959. NSRange range = [webUrl rangeOfString:@"Authorization="];
  960. if (range.location != NSNotFound) {
  961. webUrl = [webUrl substringToIndex:range.location-1];
  962. }
  963. }
  964. // 获取次数
  965. NSString *failCount = UserDefault(@"WEB_FAILCOUNT");
  966. if ([NSString isEmptyString:failCount]) {
  967. failCount = @"1";
  968. UserDefaultSetObjectForKey(failCount, @"WEB_FAILCOUNT");
  969. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  970. }
  971. else if (failCount.integerValue == 1) {
  972. NSString *preUrl = UserDefaultObjectForKey(FAIL_WEB_URL);
  973. if (![webUrl isEqualToString:preUrl]) { // 如果打开和之前失败不相同重新统计数据
  974. UserDefaultSetObjectForKey(@"1", @"WEB_FAILCOUNT");
  975. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  976. }
  977. else {
  978. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  979. }
  980. }
  981. else {
  982. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  983. }
  984. // 当前失败的H5地址
  985. UserDefaultSetObjectForKey(webUrl, FAIL_WEB_URL);
  986. // 退出登录
  987. [APPLOGIN_MANAGER logoutAction];
  988. }
  989. #pragma mark ----- WKWebView delegate
  990. // 1 在发送请求之前,决定是否跳转
  991. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  992. NSLog(@"1-------在发送请求之前,决定是否跳转 -->%@",navigationAction.request);
  993. NSURL *url = navigationAction.request.URL;
  994. NSString *scheme = [url scheme];
  995. UIApplication *app = [UIApplication sharedApplication];
  996. NSString *urlString = url.absoluteString;
  997. if (![urlString containsString:@"colexiu.com"] && ![urlString containsString:WEBHOST]) { // 外部链接
  998. self.isOutLink = YES;
  999. }
  1000. else {
  1001. self.isOutLink = NO;
  1002. }
  1003. // 打电话
  1004. if ([scheme isEqualToString:@"tel"]) {
  1005. if ([app canOpenURL:url]) {
  1006. [app openURL:url];
  1007. // 一定要加上这句,否则会打开新页面
  1008. decisionHandler(WKNavigationActionPolicyCancel);
  1009. return;
  1010. }
  1011. }
  1012. decisionHandler(WKNavigationActionPolicyAllow);
  1013. }
  1014. // 2 页面开始加载时调用
  1015. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  1016. NSLog(@"2-------页面开始加载时调用");
  1017. }
  1018. // 3 在收到响应后,决定是否跳转
  1019. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  1020. /// 在收到服务器的响应头,根据response相关信息,决定是否跳转。decisionHandler必须调用,来决定是否跳转,参数WKNavigationActionPolicyCancel取消跳转,WKNavigationActionPolicyAllow允许跳转
  1021. NSLog(@"3-------在收到响应后,决定是否跳转");
  1022. decisionHandler(WKNavigationResponsePolicyAllow);
  1023. }
  1024. // 4 当内容开始返回时调用
  1025. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
  1026. NSLog(@"4-------当内容开始返回时调用");
  1027. }
  1028. // 5 页面加载完成之后调用
  1029. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  1030. NSLog(@"5-------页面加载完成之后调用");
  1031. if (_hasModify == NO) {
  1032. [self configLocalStorage];
  1033. }
  1034. }
  1035. // 调用js方法
  1036. - (void)postMessageJS:(NSDictionary *)jsDict {
  1037. NSString *jsString = [jsDict mj_JSONString];
  1038. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"sendMessage(%@)", jsString] completionHandler:nil];
  1039. }
  1040. // 6 页面加载失败时调用
  1041. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  1042. NSLog(@"6-------页面加载失败时调用");
  1043. [self showErrorView];
  1044. }
  1045. // 接收到服务器跳转请求之后调用
  1046. - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
  1047. NSLog(@"-------接收到服务器跳转请求之后调用");
  1048. }
  1049. // 数据加载发生错误时调用
  1050. - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
  1051. NSLog(@"----数据加载发生错误时调用");
  1052. // 错误上报
  1053. if (error) {
  1054. NSLog(@"-- error desc - %@", error.description);
  1055. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  1056. [parm setValue:UserDefault(UIDKey) forKey:@"userId"];
  1057. [parm setValue:@"KSBaseWKWebViewController" forKey:@"Location"];
  1058. [parm setValue:webView.URL.absoluteString forKey:@"url"];
  1059. [parm setValue:@(error.code) forKey:@"errorCode"];
  1060. [parm setValue:error.description forKey:@"errorDesc"];
  1061. [parm setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"version"];
  1062. NSString *content = [parm mj_JSONString];
  1063. NSMutableDictionary *uploadParm = [KSLogManager generateLogMessageWithContent:content type:@"ERROR"];
  1064. NSMutableArray *uploadArray = [NSMutableArray arrayWithObject:uploadParm];
  1065. [KSNetworkingManager sysExceptionLogUpdate:KS_POST token:UserDefault(TokenKey) logArray:uploadArray success:^(NSDictionary * _Nonnull dic) {
  1066. if ([dic ks_integerValueForKey:@"code"] == 200) {
  1067. }
  1068. } faliure:^(NSError * _Nonnull error) {
  1069. }];
  1070. }
  1071. }
  1072. - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
  1073. {
  1074. dispatch_queue_t queue = dispatch_queue_create("webViewChallengeQueue", NULL);
  1075. dispatch_async(queue, ^{
  1076. if (SSL_AUTH) {
  1077. NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  1078. NSURLCredential *customCredential = nil;
  1079. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  1080. // 默认信任
  1081. customCredential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  1082. disposition = NSURLSessionAuthChallengeUseCredential;
  1083. }
  1084. else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
  1085. // client authentication
  1086. SecIdentityRef identity = NULL;
  1087. SecTrustRef trust = NULL;
  1088. if ([AuthChallengeManager extractIdentity:&identity andTrust:&trust filePath:CERT_PATH]) {
  1089. SecCertificateRef certificate = NULL;
  1090. SecIdentityCopyCertificate(identity, &certificate);
  1091. const void*certs[] = {certificate};
  1092. CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
  1093. customCredential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
  1094. disposition = NSURLSessionAuthChallengeUseCredential;
  1095. }
  1096. }
  1097. if (completionHandler) {
  1098. completionHandler(disposition, customCredential);
  1099. }
  1100. }
  1101. else {
  1102. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  1103. if (challenge.previousFailureCount == 0) {
  1104. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  1105. completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
  1106. } else {
  1107. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  1108. }
  1109. }
  1110. else {
  1111. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  1112. }
  1113. }
  1114. });
  1115. }
  1116. //当因为某些问题,导致webView进程终止时触发
  1117. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
  1118. NSLog(@"%s", __func__);
  1119. [webView reload];
  1120. }
  1121. /**
  1122. * web界面中有弹出警告框时调用
  1123. *
  1124. * @param webView 实现该代理的webview
  1125. * @param message 警告框中的内容
  1126. * @param completionHandler 警告框消失调用
  1127. */
  1128. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
  1129. NSLog(@"-------web界面中有弹出警告框时调用");
  1130. NSLog(@"%@",message);
  1131. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  1132. message:nil
  1133. preferredStyle:UIAlertControllerStyleAlert];
  1134. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  1135. style:UIAlertActionStyleCancel
  1136. handler:^(UIAlertAction *action) {
  1137. completionHandler();
  1138. }]];
  1139. [self presentViewController:alertController animated:YES completion:nil];
  1140. }
  1141. // 取消和确认的按钮
  1142. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
  1143. // js 里面的alert实现,如果不实现,网页的alert函数无效 ,
  1144. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  1145. message:nil
  1146. preferredStyle:UIAlertControllerStyleAlert];
  1147. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  1148. style:UIAlertActionStyleDefault
  1149. handler:^(UIAlertAction *action) {
  1150. completionHandler(YES);
  1151. }]];
  1152. [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
  1153. style:UIAlertActionStyleCancel
  1154. handler:^(UIAlertAction *action){
  1155. completionHandler(NO);
  1156. }]];
  1157. [self presentViewController:alertController animated:YES completion:^{}];
  1158. }
  1159. #pragma mark - KVO回馈
  1160. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  1161. if ([keyPath isEqualToString:@"estimatedProgress"]) {
  1162. self.progressLayer.opacity = 1;
  1163. if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
  1164. return;
  1165. }
  1166. self.progressLayer.frame = CGRectMake(0, 0, kScreenWidth*[change[@"new"] floatValue], 3);
  1167. if ([change[@"new"]floatValue] == 1.0) {
  1168. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1169. self.progressLayer.opacity = 0;
  1170. self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
  1171. });
  1172. }
  1173. }
  1174. }
  1175. /*
  1176. #pragma mark - Navigation
  1177. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1178. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1179. // Get the new view controller using [segue destinationViewController].
  1180. // Pass the selected object to the new view controller.
  1181. }
  1182. */
  1183. - (void)configLocalStorage {
  1184. _hasModify = YES;
  1185. if (![NSString isEmptyString:UserDefault(TokenKey)]) {
  1186. NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('Authorization', '%@ %@')",UserDefault(Token_type), UserDefault(TokenKey)];
  1187. [self.myWebView evaluateJavaScript:jsString completionHandler:nil];
  1188. }
  1189. }
  1190. - (void)setupProgress {
  1191. UIView *progress = [[UIView alloc]init];
  1192. progress.frame = CGRectMake(0, 0, kScreenWidth, 3);
  1193. progress.backgroundColor = [UIColor clearColor];
  1194. [self.view addSubview:progress];
  1195. CALayer *layer = [CALayer layer];
  1196. layer.frame = CGRectMake(0, 0, 0, 3);
  1197. layer.backgroundColor = CLIENT_THEMECOLOR.CGColor;
  1198. [progress.layer addSublayer:layer];
  1199. self.progressLayer = layer;
  1200. }
  1201. + (WKProcessPool*)singleWkProcessPool {
  1202. static WKProcessPool *sharedPool;
  1203. static dispatch_once_t onceToken;
  1204. dispatch_once(&onceToken, ^{
  1205. sharedPool = [[WKProcessPool alloc] init];
  1206. });
  1207. return sharedPool;
  1208. }
  1209. - (NSDictionary *)convertJsonStringToNSDictionary:(NSString *)jsonString {
  1210. if (jsonString == nil) {
  1211. return nil;
  1212. }
  1213. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  1214. NSError *error;
  1215. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
  1216. if (error) {
  1217. NSLog(@"jsonString解析失败:%@", error);
  1218. return nil;
  1219. }
  1220. return json;
  1221. }
  1222. - (void)dealloc {
  1223. NSLog(@"webView dealloc -----");
  1224. [[_myWebView configuration].userContentController removeScriptMessageHandlerForName:SCRIPT_NAME];
  1225. [_myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
  1226. [_myWebView removeObserver:self forKeyPath:@"title"];
  1227. [_myWebView loadHTMLString:@"" baseURL:nil];
  1228. [_myWebView removeFromSuperview];
  1229. _myWebView = nil;
  1230. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  1231. [[NSURLCache sharedURLCache] setDiskCapacity:0];
  1232. [[NSURLCache sharedURLCache] setMemoryCapacity:0];
  1233. [[NSNotificationCenter defaultCenter] removeObserver:self];
  1234. }
  1235. - (NSString *)getSaveSpeedPath {
  1236. // 在Documents目录下创建一个名为AudioSpeedFile的文件夹
  1237. NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioSpeedFile"];
  1238. NSLog(@"%@",path);
  1239. NSFileManager *fileManager = [NSFileManager defaultManager];
  1240. BOOL isDir = FALSE;
  1241. BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
  1242. if(!(isDirExist && isDir)) {
  1243. BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  1244. if(!bCreateDir){
  1245. NSLog(@"创建文件夹失败!");
  1246. }
  1247. NSLog(@"创建文件夹成功,文件路径%@",path);
  1248. }
  1249. path = [path stringByAppendingPathComponent:@"songSpeed.plist"];
  1250. NSLog(@"file path:%@",path);
  1251. return path;
  1252. }
  1253. #pragma mark -- 上传图片
  1254. - (void)hudTipWillShow:(BOOL)willShow{
  1255. if (willShow) {
  1256. [self resignFirstResponder];
  1257. UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
  1258. if (!_HUD) {
  1259. _HUD = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
  1260. _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
  1261. _HUD.label.text = @"正在上传视频...";
  1262. _HUD.contentColor = [UIColor whiteColor];
  1263. _HUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
  1264. _HUD.bezelView.backgroundColor = HexRGBAlpha(0x000000, 0.8);
  1265. _HUD.removeFromSuperViewOnHide = YES;
  1266. }else{
  1267. _HUD.progress = 0;
  1268. [keyWindow addSubview:_HUD];
  1269. [_HUD showAnimated:YES];
  1270. }
  1271. }else{
  1272. [_HUD hideAnimated:YES];
  1273. }
  1274. }
  1275. - (void)uploadImageArray:(NSMutableArray *)imageArray bucket:(NSString *)bucket {
  1276. [LOADING_MANAGER showHUD];
  1277. NSMutableArray *imageDataArray = [NSMutableArray array];
  1278. for (UIImage *image in imageArray) {
  1279. NSData *imgData = [UIImage turnsImaegDataByImage:image];
  1280. [imageDataArray addObject:imgData];
  1281. }
  1282. [UPLOAD_MANAGER configWithfilePath:@"/user/"];
  1283. [UPLOAD_MANAGER mutilUploadImage:imageDataArray fileName:@"complainImg" successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1284. [LOADING_MANAGER removeHUD];
  1285. NSMutableArray *urlArray = [NSMutableArray array];
  1286. for (NSString *url in fileUrlArray) {
  1287. [urlArray addObject:url];
  1288. }
  1289. NSString *attachments = [urlArray componentsJoinedByString:@","];
  1290. if (self.chooseFileParm) { // 回调
  1291. [self.chooseFileParm setValue:attachments forKey:@"fileUrl"];
  1292. [self postMessage:self.chooseFileParm];
  1293. self.chooseFileParm = nil;
  1294. }
  1295. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1296. [LOADING_MANAGER removeHUD];
  1297. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1298. [self fileChooseErrorCallback];
  1299. }];
  1300. }
  1301. #pragma mark --- 上传视频文件
  1302. - (void)uploadVideoWithUrl:(NSString *)videoUrl bucket:(NSString *)bucket {
  1303. // 取出视频第一帧
  1304. UIImage *previewImage = [self firstFrameWithVideoURL:[NSURL fileURLWithPath:videoUrl] size:CGSizeMake(1280, 720)];
  1305. __block NSString *imageUrl = @"";
  1306. if (previewImage) { // 如果有第一帧
  1307. NSData *imgData = [UIImage turnsImaegDataByImage:previewImage];
  1308. NSString *fileName = @"videoPreviewImg";
  1309. [UPLOAD_MANAGER configWithfilePath:@"/user/"];
  1310. [UPLOAD_MANAGER uploadImage:imgData fileName:fileName successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1311. NSString *url = [fileUrlArray lastObject];
  1312. imageUrl = url;
  1313. [self submitUrlWith:imageUrl videoUrl:videoUrl];
  1314. } faliure:^(NSError * _Nullable error, NSString *descMessaeg) {
  1315. if (![NSString isEmptyString:descMessaeg]) {
  1316. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1317. }
  1318. [self fileChooseErrorCallback];
  1319. }];
  1320. }
  1321. else {
  1322. [self submitUrlWith:nil videoUrl:videoUrl];
  1323. }
  1324. }
  1325. - (void)submitUrlWith:(NSString *)imgUrl videoUrl:(NSString *)videoUrl {
  1326. // 上传视频
  1327. [self hudTipWillShow:YES];
  1328. NSURL *uploadFileUrl = [NSURL fileURLWithPath:videoUrl];
  1329. NSData *fileData = [NSData dataWithContentsOfURL:uploadFileUrl];
  1330. NSString *suffix = [NSString stringWithFormat:@".%@",[uploadFileUrl pathExtension]];
  1331. [UPLOAD_MANAGER videoUpload:fileData fileName:@"video" fileSuffix:suffix progress:^(int64_t bytesWritten, int64_t totalBytes) {
  1332. dispatch_main_async_safe(^{
  1333. // 显示进度
  1334. if (self.HUD) {
  1335. self.HUD.progress = bytesWritten / totalBytes;// progress是回调进度
  1336. }
  1337. });
  1338. } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1339. [self hudTipWillShow:NO];
  1340. NSString *fileUrl = [fileUrlArray lastObject];
  1341. [self videoUploadCallback:fileUrl firstFrameImg:imgUrl];
  1342. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1343. [self hudTipWillShow:NO];
  1344. if (![NSString isEmptyString:descMessaeg]) {
  1345. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1346. }
  1347. [self videoUploadCallback:@"" firstFrameImg:@""];
  1348. }];
  1349. }
  1350. - (void)videoUploadCallback:(NSString *)remoteVideoUrl firstFrameImg:(NSString *)imgUrl {
  1351. if (self.chooseFileParm) { // 回调
  1352. [self.chooseFileParm setValue:remoteVideoUrl forKey:@"fileUrl"];
  1353. [self.chooseFileParm setValue:imgUrl forKey:@"firstFrameImg"];
  1354. [self postMessage:self.chooseFileParm];
  1355. self.chooseFileParm = nil;
  1356. }
  1357. }
  1358. #pragma mark ---- 获取图片第一帧
  1359. - (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
  1360. {
  1361. // 获取视频第一帧
  1362. NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
  1363. AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
  1364. AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
  1365. generator.appliesPreferredTrackTransform = YES;
  1366. generator.maximumSize = CGSizeMake(size.width, size.height);
  1367. NSError *error = nil;
  1368. CGImageRef imgRef = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
  1369. if (imgRef) {
  1370. UIImage *image = [UIImage imageWithCGImage:imgRef];
  1371. CGImageRelease(imgRef);
  1372. return image;
  1373. }
  1374. else {
  1375. return nil;
  1376. }
  1377. }
  1378. #pragma mark ---- UIDocumentPickerDelegate
  1379. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
  1380. if (self.isDownloadFile) {
  1381. self.isDownloadFile = NO;
  1382. }
  1383. else {
  1384. [self fileChooseErrorCallback];
  1385. }
  1386. }
  1387. - (void)fileChooseErrorCallback {
  1388. if (self.chooseFileParm) { // 回调
  1389. [self.chooseFileParm setValue:@"" forKey:@"fileUrl"];
  1390. [self postMessage:self.chooseFileParm];
  1391. self.chooseFileParm = nil;
  1392. }
  1393. }
  1394. - (void)uploadFile:(NSString *)fileName fileUrl:(NSString *)fileUrl {
  1395. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1396. [LOADING_MANAGER showHUD];
  1397. NSString *suffix = [NSString stringWithFormat:@".%@",[[fileName componentsSeparatedByString:@"."] lastObject]];
  1398. NSData *fileData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:fileUrl]];
  1399. [UPLOAD_MANAGER configWithfilePath:@"/user/"];
  1400. [UPLOAD_MANAGER uploadFile:fileData fileName:@"file" fileSuffix:suffix progress:^(int64_t bytesWritten, int64_t totalBytes) {
  1401. int progress = (int)(bytesWritten / totalBytes * 100);
  1402. __block NSString *tipsMessage = [NSString stringWithFormat:@"上传中 %d%%",progress];
  1403. dispatch_main_async_safe(^{
  1404. [LOADING_MANAGER.loadingView setDisplayText:tipsMessage];
  1405. });
  1406. } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1407. [LOADING_MANAGER removeHUD];
  1408. NSString *fileUrl = [fileUrlArray lastObject];
  1409. if (self.chooseFileParm) { // 回调
  1410. [self.chooseFileParm setValue:fileUrl forKey:@"fileUrl"];
  1411. [self postMessage:self.chooseFileParm];
  1412. self.chooseFileParm = nil;
  1413. }
  1414. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1415. [LOADING_MANAGER removeHUD];
  1416. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1417. [self fileChooseErrorCallback];
  1418. }];
  1419. });
  1420. }
  1421. - (CGFloat)getFileSize:(NSURL *)fileUrl {
  1422. NSFileManager *fileManager = [NSFileManager defaultManager];
  1423. float filesize = -1.0;
  1424. NSString *path = fileUrl.path;
  1425. if ([fileManager fileExistsAtPath:path]) {
  1426. NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
  1427. unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
  1428. filesize = 1.0*size/1024/1024;
  1429. }
  1430. return filesize;
  1431. }
  1432. #pragma mark - UIDocumentInteractionControllerDelegate
  1433. -(UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller{
  1434. return self;
  1435. }
  1436. -(UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {
  1437. return self.view;
  1438. }
  1439. -(CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
  1440. return self.view.frame;
  1441. }
  1442. #pragma mark - UIDocumentPickerDelegate
  1443. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
  1444. if (self.isDownloadFile) {
  1445. self.isDownloadFile = NO;
  1446. //保存成功
  1447. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"保存成功"];
  1448. }
  1449. else {
  1450. NSURL *url = [urls lastObject];
  1451. NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
  1452. NSString *fileName = [array lastObject];
  1453. fileName = [fileName stringByRemovingPercentEncoding];
  1454. if (self.fileChooseType == CHOOSETYPE_XML) {
  1455. if (![fileName hasSuffix:@".xml"]) {
  1456. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传XML格式文件"];
  1457. [self fileChooseErrorCallback];
  1458. return;
  1459. }
  1460. }
  1461. else if (self.fileChooseType == CHOOSETYPE_MIDI) {
  1462. if (![fileName hasSuffix:@".mid"] || [fileName hasSuffix:@".midi"]) {
  1463. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传mid格式文件"];
  1464. [self fileChooseErrorCallback];
  1465. return;
  1466. }
  1467. }
  1468. else if (self.fileChooseType == CHOOSETYPE_MP3) {
  1469. if (![fileName hasSuffix:@".mp3"]) {
  1470. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传mp3格式文件"];
  1471. [self fileChooseErrorCallback];
  1472. return;
  1473. }
  1474. }
  1475. else {
  1476. if (![fileName hasSuffix:@".mp3"] && ![fileName hasSuffix:@".aac"]) {
  1477. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"暂不支持此格式!"];
  1478. [self fileChooseErrorCallback];
  1479. return;
  1480. }
  1481. }
  1482. __block NSString * fileUrl = @"";
  1483. if ([KSICloudManager iCloudEnable]) {
  1484. [KSICloudManager downloadWithDocumentURL:url callBack:^(id obj) {
  1485. NSData *data = obj;
  1486. //写入沙盒Documents
  1487. NSString *pathStr = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",fileName]];
  1488. [data writeToFile:pathStr atomically:YES];
  1489. if (![[NSFileManager defaultManager] fileExistsAtPath:pathStr]) {
  1490. BOOL isSuccess = [data writeToFile:pathStr atomically:YES];
  1491. if (isSuccess) {
  1492. fileUrl = pathStr;
  1493. }
  1494. else {
  1495. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"写入文件错误!"];
  1496. [self fileChooseErrorCallback];
  1497. }
  1498. }
  1499. else {
  1500. fileUrl = pathStr;
  1501. }
  1502. [self uploadFile:fileName fileUrl:pathStr];
  1503. }];
  1504. }
  1505. else {
  1506. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"iCloud不可用!"];
  1507. [self fileChooseErrorCallback];
  1508. }
  1509. }
  1510. }
  1511. #pragma mark ---- 镜像和投屏检测
  1512. - (void)captureViewTips:(NSNotification *)notification {
  1513. [self checkCaptured];
  1514. }
  1515. - (void)checkCaptured {
  1516. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1517. if ([self checkIsCaptured]) {
  1518. [self didCapturedView];
  1519. }
  1520. });
  1521. }
  1522. - (BOOL)checkIsCaptured {
  1523. if ([UIScreen mainScreen].isCaptured && [UIScreen screens].count < 2) {
  1524. return YES;
  1525. }
  1526. return NO;
  1527. }
  1528. - (void)didCapturedView {
  1529. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  1530. [sendParm setValue:@"setVideoPlayer" forKey:@"api"];
  1531. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  1532. [content setValue:@"pause" forKey:@"status"];
  1533. [sendParm setValue:content forKey:@"content"];
  1534. [self postMessage:sendParm];
  1535. }
  1536. - (KSWebLoadRefreshView *)errorView {
  1537. if (!_errorView) {
  1538. _errorView = [KSWebLoadRefreshView shareInstance];
  1539. MJWeakSelf;
  1540. [_errorView failViewActionCallback:^(BOOL isBack) {
  1541. [weakSelf hideErrorView];
  1542. if (isBack) {
  1543. [weakSelf backAction];
  1544. }
  1545. else {
  1546. [weakSelf loadRequest];
  1547. }
  1548. }];
  1549. }
  1550. return _errorView;
  1551. }
  1552. - (void)showErrorView {
  1553. if (![self.view.subviews containsObject:self.errorView]) {
  1554. [self.view addSubview:self.errorView];
  1555. [self.errorView mas_makeConstraints:^(MASConstraintMaker *make) {
  1556. make.left.right.top.bottom.mas_equalTo(self.view);
  1557. }];
  1558. [self.view bringSubviewToFront:self.errorView];
  1559. }
  1560. }
  1561. - (void)hideErrorView {
  1562. if ([self.view.subviews containsObject:self.errorView]) {
  1563. [self.errorView removeFromSuperview];
  1564. }
  1565. }
  1566. /*
  1567. #pragma mark - Navigation
  1568. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1569. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1570. // Get the new view controller using [segue destinationViewController].
  1571. // Pass the selected object to the new view controller.
  1572. }
  1573. */
  1574. @end