KSBaseWKWebViewController.m 78 KB

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