KSBaseWKWebViewController.m 87 KB

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