KSBaseWKWebViewController.m 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055
  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. else if ([parm ks_stringValueForKey:@"checkDeviceCamera"]) { // 检测相机权限
  677. NSMutableDictionary *sendContent = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  678. [RecordCheckManager checkCameraPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
  679. if (type == PREMISSIONTYPE_YES) {
  680. [sendContent setValue:@(YES) forKey:@"status"];
  681. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  682. [sendParm setValue:sendContent forKey:@"content"];
  683. [self postMessage:sendParm];
  684. }
  685. else if (type == PREMISSIONTYPE_NO) {
  686. [sendContent setValue:@(NO) forKey:@"status"];
  687. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  688. [sendParm setValue:sendContent forKey:@"content"];
  689. [self postMessage:sendParm];
  690. }
  691. }];
  692. }
  693. }
  694. - (void)openOutLink:(NSString *)url {
  695. // 外部浏览器打开
  696. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[url getUrlEndcodeString]] options: @{} completionHandler: nil];
  697. }
  698. - (void)downloadFileWithUrl:(NSString *)fileUrl parm:(NSDictionary *)parm {
  699. [LOADING_MANAGER showCustomLoading:@"文件下载中"];
  700. [KSNetworkingManager downloadFileRequestWithFileUrl:fileUrl progress:^(int64_t bytesRead, int64_t totalBytes) {
  701. // 显示进度
  702. NSInteger progress = (NSInteger)(bytesRead*1.0 / totalBytes) * 100;
  703. NSString *tipsString = [NSString stringWithFormat:@"文件下载中\n%zd%%",progress];
  704. dispatch_main_async_safe(^{
  705. [LOADING_MANAGER showCustomLoading:tipsString];
  706. });
  707. } success:^(NSURL * _Nonnull fileUrl) {
  708. [LOADING_MANAGER removeCustomLoading];
  709. // 修改文件名
  710. NSURL *saveUrl = fileUrl;
  711. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  712. NSString *fileName = [content ks_stringValueForKey:@"fileName"];
  713. if (![NSString isEmptyString:fileName]) { // 重命名
  714. saveUrl = [self renameFile:fileUrl withNewName:fileName];
  715. }
  716. [self saveFileWithPath:saveUrl sendParm:parm];
  717. } faliure:^(NSError * _Nonnull error) {
  718. [LOADING_MANAGER removeCustomLoading];
  719. [self downloadCallback:NO withParm:parm];
  720. }];
  721. }
  722. - (void)downloadCallback:(BOOL)isSuccess withParm:(NSDictionary *)parm {
  723. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  724. NSMutableDictionary *content = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
  725. [content setValue:@(isSuccess) forKey:@"isSuccess"];
  726. [sendParm setValue:content forKey:@"content"];
  727. [self postMessage:sendParm];
  728. }
  729. - (NSURL *)renameFile:(NSURL *)fileUrl withNewName:(NSString *)fileName {
  730. // 获取文件的路径
  731. NSURL *directoryURL = [fileUrl URLByDeletingLastPathComponent];
  732. // 旧文件名
  733. NSString *oldFileName = [fileUrl lastPathComponent];
  734. NSString *fileExtension = [oldFileName pathExtension];
  735. // 当前时间戳
  736. NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] *1000;
  737. // 构建新的文件名
  738. NSString *newFileName = [NSString stringWithFormat:@"%.0f_%@.%@", interval, fileName, fileExtension];
  739. // 构建新文件的完整 URL
  740. NSURL *newURL = [directoryURL URLByAppendingPathComponent:newFileName];
  741. // 使用 NSFileManager 移动文件以重命名
  742. NSFileManager *fileManager = [NSFileManager defaultManager];
  743. // 如果存在newURL 移除
  744. if ([fileManager fileExistsAtPath:[newURL path]]) {
  745. [fileManager removeItemAtURL:newURL error:nil];
  746. }
  747. NSError *error = nil;
  748. BOOL success = [fileManager moveItemAtURL:fileUrl toURL:newURL error:&error];
  749. if (success) {
  750. return newURL;
  751. }
  752. else {
  753. return fileUrl;
  754. }
  755. }
  756. - (void)saveFileWithPath:(NSURL *)fileUrl sendParm:(NSDictionary *)parm {
  757. self.downloadParm = parm;
  758. self.isDownloadFile = YES;
  759. self.downloadFileUrl = fileUrl;
  760. // 保存到文件目录下
  761. KSDocumentViewController *documentPickerVC = [[KSDocumentViewController alloc] initWithURL:fileUrl inMode:UIDocumentPickerModeExportToService];
  762. documentPickerVC.buttonColor = CLIENT_THEMECOLOR;
  763. documentPickerVC.currentType = KSDOCUMENT_TYPE_DOWNLOADFILE;
  764. // 设置代理
  765. documentPickerVC.delegate = self;
  766. // 设置模态弹出方式
  767. documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
  768. [self.navigationController presentViewController:documentPickerVC animated:YES completion:nil];
  769. }
  770. - (void)downloadWithParm:(NSDictionary *)parm {
  771. MJWeakSelf;
  772. [COURSEWARE_MANAGER downloadCourseWithParm:parm callback:^(NSDictionary * _Nonnull sendParm) {
  773. [weakSelf postMessage:sendParm];
  774. }];
  775. }
  776. - (void)removeLoadHud {
  777. [LOADING_MANAGER removeCustomLoading];
  778. }
  779. - (void)videCropImage:(UIImage *)cover content:(NSDictionary *)content {
  780. NSData *imgData = [UIImage turnsImaegDataByImage:cover];
  781. NSString *fileName = @"videoCoverImage";
  782. [LOADING_MANAGER showCancelCustomLoading:@"上传中..." cancel:^{
  783. [UPLOAD_MANAGER cancelUploadCallback:^{
  784. [self removeLoadHud];
  785. }];
  786. }];
  787. [UPLOAD_MANAGER configWithfilePath:@"/user/"];
  788. [UPLOAD_MANAGER uploadFile:imgData fileName:fileName fileSuffix:[UIImage typeForImageData:imgData] progress:^(int64_t bytesWritten, int64_t totalBytes) {
  789. // 显示进度
  790. int progress = (int)(bytesWritten / totalBytes * 100);
  791. __block NSString *tipsMessage = [NSString stringWithFormat:@"上传中 %d%%",progress];
  792. dispatch_main_async_safe(^{
  793. [LOADING_MANAGER.loadingView setDisplayText:tipsMessage];
  794. });
  795. } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  796. [LOADING_MANAGER removeCustomLoading];
  797. NSString *fileUrl = [fileUrlArray lastObject];
  798. NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:content];
  799. [dic setValue:fileUrl forKey:@"videoCover"];
  800. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  801. [sendParm setValue:@"videoCrop" forKey:@"api"];
  802. [sendParm setValue:dic forKey:@"content"];
  803. [self postMessage:sendParm];
  804. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  805. [LOADING_MANAGER removeCustomLoading];
  806. }];
  807. }
  808. - (void)downFile:(NSString *)fileUrl {
  809. [LOADING_MANAGER showCustomLoading:@"文件下载中..."];
  810. [KSNetworkingManager downloadFileRequestWithFileUrl:fileUrl progress:^(int64_t bytesRead, int64_t totalBytes) {
  811. } success:^(NSURL * _Nonnull fileUrl) {
  812. [LOADING_MANAGER removeCustomLoading];
  813. [self saveFileWithUrl:fileUrl];
  814. } faliure:^(NSError * _Nonnull error) {
  815. [LOADING_MANAGER removeCustomLoading];
  816. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"下载失败"];
  817. }];
  818. }
  819. - (void)saveFileWithUrl:(NSURL *)fileUrl {
  820. if ([fileUrl.absoluteString hasSuffix:@".mp4"]) { // 视频
  821. [RecordCheckManager checkPhotoLibraryPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
  822. if (type == PREMISSIONTYPE_YES) {
  823. [self saveVideo:fileUrl];
  824. }
  825. else {
  826. [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
  827. }
  828. }];
  829. }
  830. else { // 音频
  831. [self saveFileToPhone:fileUrl];
  832. }
  833. }
  834. - (void)saveVideo:(NSURL *)fileUrl {
  835. [LOADING_MANAGER showCustomLoading:@"视频保存中..."];
  836. [[TZImageManager manager] saveVideoWithUrl:fileUrl completion:^(PHAsset *asset, NSError *error) {
  837. if (!error) {
  838. dispatch_main_async_safe(^{
  839. [LOADING_MANAGER removeCustomLoading];
  840. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"已保存到相册"];
  841. });
  842. }
  843. else {
  844. dispatch_main_async_safe(^{
  845. [LOADING_MANAGER removeCustomLoading];
  846. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"保存视频错误"];
  847. });
  848. }
  849. }];
  850. }
  851. - (void)saveFileToPhone:(NSURL *)fileUrl {
  852. // 判断是否是音频
  853. AVAsset * asset =[AVAsset assetWithURL:fileUrl];
  854. KSDOCUMENT_TYPE currentType = KSDOCUMENT_TYPE_DOWNLOADFILE;
  855. if ([asset tracksWithMediaType:AVMediaTypeAudio].count > 0) {
  856. currentType = KSDOCUMENT_TYPE_DOWNLOADAUDIO;
  857. }
  858. self.isDownloadFile = YES;
  859. self.downloadFileUrl = fileUrl;
  860. KSDocumentViewController *documentPicker = [[KSDocumentViewController alloc] initWithURL:fileUrl inMode:UIDocumentPickerModeExportToService];
  861. documentPicker.buttonColor = CLIENT_THEMECOLOR;
  862. documentPicker.currentType = currentType;
  863. documentPicker.delegate = self;
  864. documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
  865. [self presentViewController:documentPicker animated:YES completion:nil];
  866. }
  867. - (void)chooseFileWithType:(NSString *)typeStr maxNumber:(NSInteger)maxCount bucket:(NSString *)bucket {
  868. if ([typeStr isEqualToString:@"img"]) { // 选择图片上传
  869. if (maxCount > 9) {
  870. maxCount = 9;
  871. }
  872. [self chooseMediaWithType:MEDIATYPE_PHOTO maxCount:maxCount bucket:bucket];
  873. }
  874. else if ([typeStr isEqualToString:@"video"]) {
  875. [self chooseMediaWithType:MEDIATYPE_VIDEO maxCount:1 bucket:bucket];
  876. }
  877. else if ([typeStr isEqualToString:@"file"]) {
  878. [self chooseDocumentWithType:CHOOSETYPE_ALL bucket:bucket];
  879. }
  880. else if ([typeStr isEqualToString:@"midi"]) {
  881. [self chooseDocumentWithType:CHOOSETYPE_MIDI bucket:bucket];
  882. }
  883. else if ([typeStr isEqualToString:@"mp3"]) {
  884. [self chooseDocumentWithType:CHOOSETYPE_MP3 bucket:bucket];
  885. }
  886. else if (([typeStr isEqualToString:@"xml"] || [typeStr isEqualToString:@"musicxml"])) {
  887. [self chooseDocumentWithType:CHOOSETYPE_XML bucket:bucket];
  888. }
  889. }
  890. - (void)chooseDocumentWithType:(CHOOSETYPE)fileTyle bucket:(NSString *)bucket {
  891. self.bucketName = bucket;
  892. self.fileChooseType = fileTyle;
  893. 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"];
  894. KSDocumentViewController *documentPickerViewController = [[KSDocumentViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeImport];
  895. documentPickerViewController.buttonColor = CLIENT_THEMECOLOR;
  896. documentPickerViewController.currentType = KSDOCUMENT_TYPE_UPLOAD;
  897. documentPickerViewController.delegate = self;
  898. documentPickerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  899. [self presentViewController:documentPickerViewController animated:YES completion:nil];
  900. }
  901. - (void)chooseMediaWithType:(MEDIATYPE)type maxCount:(NSInteger)maxCount bucket:(NSString *)bucketName {
  902. self.mediaManager = [[KSMediaManager alloc] init];
  903. self.mediaManager.mediaType = type;
  904. self.mediaManager.maxPhotoNumber = maxCount;
  905. self.mediaManager.baseCtrl = self;
  906. self.mediaManager.needCropImage = NO;
  907. self.mediaManager.videoMaxDuration = 40 * 60;
  908. MJWeakSelf;
  909. [self.mediaManager noAlertCallback:^(NSString * _Nullable videoUrl, NSMutableArray * _Nullable imageArray, NSMutableArray * _Nullable imageAsset) {
  910. if (type == MEDIATYPE_PHOTO) {
  911. [weakSelf uploadImageArray:imageArray bucket:bucketName];
  912. }
  913. else {
  914. NSLog(@"%@", videoUrl);
  915. // 上传视频
  916. [weakSelf uploadVideoWithUrl:videoUrl bucket:bucketName];
  917. }
  918. }];
  919. [self.mediaManager pushImagePickerController];
  920. }
  921. - (void)savePicCallback:(NSString *)uuid isSuccess:(BOOL)isSuccess {
  922. NSString *status = isSuccess ? @"success" : @"fail";
  923. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  924. [parm setValue:@"savePicture" forKey:@"api"];
  925. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  926. [content setValue:status forKey:@"status"];
  927. [content setValue:uuid forKey:@"uuid"];
  928. [parm setValue:content forKey:@"content"];
  929. [self postMessage:parm];
  930. }
  931. - (void)sendAddressAction:(AddressListModel *)model {
  932. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  933. [sendParm setValue:@"getAddress" forKey:@"api"];
  934. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  935. [content setValue:model.internalBaseClassIdentifier forKey:@"id"];
  936. [content setValue:model.detailAddress forKey:@"detailAddress"];
  937. [content setValue:model.city forKey:@"city"];
  938. [content setValue:model.region forKey:@"region"];
  939. [content setValue:model.province forKey:@"province"];
  940. [content setValue:model.name forKey:@"name"];
  941. [content setValue:model.phoneNumber forKey:@"phoneNumber"];
  942. [content setValue:model.postCode forKey:@"postCode"];
  943. [sendParm setValue:content forKey:@"content"];
  944. [self postMessage:sendParm];
  945. }
  946. - (UIImage *)imageWithBase64String:(NSString *)base64String {
  947. NSURL *URL = [NSURL URLWithString:base64String];
  948. NSData *imageData = [NSData dataWithContentsOfURL:URL];
  949. UIImage *image = [UIImage imageWithData:imageData scale:2];
  950. return image;
  951. }
  952. - (void)shareFunctionWithParm:(NSDictionary *)parm {
  953. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  954. NSString *typeString = [content ks_stringValueForKey:@"type"];
  955. KSSHARETYPE shareType = [typeString isEqualToString:@"image"] ? KSSHARETYPE_IMAGE : KSSHARETYPE_VODEO;
  956. NSString *shareTitle = [content ks_stringValueForKey:@"title"];
  957. NSString *descMessage = [content ks_stringValueForKey:@"desc"];
  958. NSString *videoUrl = [content ks_stringValueForKey:@"video"];
  959. NSString *saveLinkUrl = [content ks_stringValueForKey:@"url"];
  960. NSString *imgStr = [content ks_stringValueForKey:@"image"];
  961. UIImage *shareImage = [self imageWithBase64String:imgStr];
  962. NSArray *buttonArray = [content ks_arrayValueForKey:@"button"];
  963. BOOL containCopyButton = NO;
  964. for (NSString *nameString in buttonArray) {
  965. if ([nameString isEqualToString:@"copy"]) {
  966. containCopyButton = YES;
  967. break;
  968. }
  969. }
  970. MJWeakSelf;
  971. 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) {
  972. NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  973. [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
  974. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  975. [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
  976. [content setValue:descMessage forKey:@"message"];
  977. BOOL status = isSuccess;
  978. [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  979. [responParm setValue:content forKey:@"content"];
  980. [weakSelf postMessage:responParm];
  981. }];
  982. }
  983. - (KSSHARETYPE)getTypeWithTypeString:(NSString *)typeString {
  984. if ([typeString isEqualToString:@"image"]) { // 图片
  985. return KSSHARETYPE_IMAGE;
  986. }
  987. else if ([typeString isEqualToString:@"link"]) { // 链接
  988. return KSSHARETYPE_URL;
  989. }
  990. else {
  991. return KSSHARETYPE_VODEO;
  992. }
  993. }
  994. - (void)shareToWeChat:(NSDictionary *)parm {
  995. NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
  996. if ([[content ks_stringValueForKey:@"shareType"] isEqualToString:@"wechat"]) {
  997. NSString *typeString = [content ks_stringValueForKey:@"type"];
  998. KSSHARETYPE shareType = [self getTypeWithTypeString:typeString];
  999. NSString *shareTitle = [content ks_stringValueForKey:@"title"];
  1000. NSString *descMessage = [content ks_stringValueForKey:@"desc"];
  1001. NSString *url = [content ks_stringValueForKey:@"video"];
  1002. if (shareType == KSSHARETYPE_URL) {
  1003. url = [content ks_stringValueForKey:@"url"];
  1004. }
  1005. NSString *imgStr = [content ks_stringValueForKey:@"image"];
  1006. UIImage *shareImage = [self imageWithBase64String:imgStr];
  1007. NSString *thumImage = [content ks_stringValueForKey:@"thumb"];
  1008. MJWeakSelf;
  1009. self.shareManager = [KSUMShareManager shareInstanceToWechatWithImage:shareImage url:url shareTitle:shareTitle descMessage:descMessage shareType:shareType thumImage:thumImage callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
  1010. NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  1011. [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
  1012. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  1013. [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
  1014. [content setValue:descMessage forKey:@"message"];
  1015. BOOL status = isSuccess;
  1016. [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  1017. [responParm setValue:content forKey:@"content"];
  1018. [weakSelf postMessage:responParm];
  1019. }];
  1020. }
  1021. else if ([[content ks_stringValueForKey:@"shareType"] isEqualToString:@"wechat_circle"]) { // 微信朋友圈
  1022. NSString *typeString = [content ks_stringValueForKey:@"type"];
  1023. KSSHARETYPE shareType = [self getTypeWithTypeString:typeString];
  1024. NSString *shareTitle = [content ks_stringValueForKey:@"title"];
  1025. NSString *descMessage = [content ks_stringValueForKey:@"desc"];
  1026. NSString *url = [content ks_stringValueForKey:@"video"];
  1027. if (shareType == KSSHARETYPE_URL) {
  1028. url = [content ks_stringValueForKey:@"url"];
  1029. }
  1030. NSString *imgStr = [content ks_stringValueForKey:@"image"];
  1031. UIImage *shareImage = [self imageWithBase64String:imgStr];
  1032. NSString *thumImage = [content ks_stringValueForKey:@"thumb"];
  1033. MJWeakSelf;
  1034. self.shareManager = [KSUMShareManager shareInstanceToWechatCircleWithImage:shareImage url:url shareTitle:shareTitle descMessage:descMessage shareType:shareType thumImage:thumImage callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
  1035. NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  1036. [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
  1037. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  1038. [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
  1039. [content setValue:descMessage forKey:@"message"];
  1040. BOOL status = isSuccess;
  1041. [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  1042. [responParm setValue:content forKey:@"content"];
  1043. [weakSelf postMessage:responParm];
  1044. }];
  1045. }
  1046. }
  1047. - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
  1048. [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
  1049. } confirm:^{
  1050. [self openSettingView];
  1051. }];
  1052. }
  1053. - (void)openSettingView {
  1054. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
  1055. }
  1056. - (void)displaySource:(NSURL *)localUrl {
  1057. KSLocalWebViewController *ctrl = [[KSLocalWebViewController alloc] init];
  1058. ctrl.headTitle = @"协议文件";
  1059. ctrl.sourceData = [NSData dataWithContentsOfURL:localUrl];
  1060. ctrl.fileUrl = localUrl;
  1061. [self.navigationController pushViewController:ctrl animated:YES];
  1062. }
  1063. - (void)postMessage:(NSDictionary *)parm {
  1064. NSLog(@"------ parm %@", [parm mj_JSONString]);
  1065. if (_myWebView) {
  1066. dispatch_async(dispatch_get_main_queue(), ^{
  1067. NSString *jsString = [parm mj_JSONString];
  1068. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"postMessage(%@,'*')", jsString] completionHandler:nil];
  1069. });
  1070. }
  1071. }
  1072. // 刷新
  1073. - (void)refreshUrl:(NSString *)refreshUrl {
  1074. NSString *sepectString = [refreshUrl containsString:@"?"] ? @"&" : @"?";
  1075. NSString *tokenStr = UserDefault(TokenKey);
  1076. if (![NSString isEmptyString:tokenStr]) {
  1077. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1078. refreshUrl = [NSString stringWithFormat:@"%@%@%@",refreshUrl, sepectString, token];
  1079. }
  1080. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:refreshUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  1081. [self.myWebView loadRequest:request];
  1082. }
  1083. // 返回登录页面
  1084. - (void)backLoginView {
  1085. NSString *webUrl = [self.url copy];
  1086. if ([webUrl containsString:@"Authorization="]) {
  1087. NSRange range = [webUrl rangeOfString:@"Authorization="];
  1088. if (range.location != NSNotFound) {
  1089. webUrl = [webUrl substringToIndex:range.location-1];
  1090. }
  1091. }
  1092. // 获取次数
  1093. NSString *failCount = UserDefault(@"WEB_FAILCOUNT");
  1094. if ([NSString isEmptyString:failCount]) {
  1095. failCount = @"1";
  1096. UserDefaultSetObjectForKey(failCount, @"WEB_FAILCOUNT");
  1097. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  1098. }
  1099. else if (failCount.integerValue == 1) {
  1100. NSString *preUrl = UserDefaultObjectForKey(FAIL_WEB_URL);
  1101. if (![webUrl isEqualToString:preUrl]) { // 如果打开和之前失败不相同重新统计数据
  1102. UserDefaultSetObjectForKey(@"1", @"WEB_FAILCOUNT");
  1103. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  1104. }
  1105. else {
  1106. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  1107. }
  1108. }
  1109. else {
  1110. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  1111. }
  1112. // 当前失败的H5地址
  1113. UserDefaultSetObjectForKey(webUrl, FAIL_WEB_URL);
  1114. // 退出登录
  1115. [APPLOGIN_MANAGER logoutActionWithMsg:@""];
  1116. }
  1117. #pragma mark ----- WKWebView delegate
  1118. // 1 在发送请求之前,决定是否跳转
  1119. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  1120. NSLog(@"1-------在发送请求之前,决定是否跳转 -->%@",navigationAction.request);
  1121. NSURL *url = navigationAction.request.URL;
  1122. NSString *scheme = [url scheme];
  1123. UIApplication *app = [UIApplication sharedApplication];
  1124. NSString *urlString = url.absoluteString;
  1125. if (![urlString containsString:@"colexiu.com"] && ![urlString containsString:WEBHOST]) { // 外部链接
  1126. self.isOutLink = YES;
  1127. }
  1128. else {
  1129. self.isOutLink = NO;
  1130. }
  1131. // 打电话
  1132. if ([scheme isEqualToString:@"tel"]) {
  1133. if ([app canOpenURL:url]) {
  1134. [app openURL:url options:@{} completionHandler:nil];
  1135. // 一定要加上这句,否则会打开新页面
  1136. decisionHandler(WKNavigationActionPolicyCancel);
  1137. return;
  1138. }
  1139. }
  1140. decisionHandler(WKNavigationActionPolicyAllow);
  1141. }
  1142. // 2 页面开始加载时调用
  1143. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  1144. NSLog(@"2-------页面开始加载时调用");
  1145. }
  1146. // 3 在收到响应后,决定是否跳转
  1147. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  1148. /// 在收到服务器的响应头,根据response相关信息,决定是否跳转。decisionHandler必须调用,来决定是否跳转,参数WKNavigationActionPolicyCancel取消跳转,WKNavigationActionPolicyAllow允许跳转
  1149. NSLog(@"3-------在收到响应后,决定是否跳转");
  1150. decisionHandler(WKNavigationResponsePolicyAllow);
  1151. }
  1152. // 4 当内容开始返回时调用
  1153. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
  1154. NSLog(@"4-------当内容开始返回时调用");
  1155. }
  1156. // 5 页面加载完成之后调用
  1157. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  1158. NSLog(@"5-------页面加载完成之后调用");
  1159. if (_hasModify == NO) {
  1160. [self configLocalStorage];
  1161. }
  1162. }
  1163. // 调用js方法
  1164. - (void)postMessageJS:(NSDictionary *)jsDict {
  1165. NSString *jsString = [jsDict mj_JSONString];
  1166. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"sendMessage(%@)", jsString] completionHandler:nil];
  1167. }
  1168. // 6 页面加载失败时调用
  1169. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  1170. NSLog(@"6-------页面加载失败时调用");
  1171. [self showErrorView];
  1172. }
  1173. // 接收到服务器跳转请求之后调用
  1174. - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
  1175. NSLog(@"-------接收到服务器跳转请求之后调用");
  1176. }
  1177. // 数据加载发生错误时调用
  1178. - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
  1179. NSLog(@"----数据加载发生错误时调用");
  1180. // 错误上报
  1181. if (error) {
  1182. if (error.code == -999) {
  1183. NSLog(@"-- error desc - %@", error.description);
  1184. NSMutableDictionary *parm = [NSMutableDictionary dictionary];
  1185. [parm setValue:UserDefault(UIDKey) forKey:@"userId"];
  1186. [parm setValue:@"KSBaseWKWebViewController" forKey:@"Location"];
  1187. [parm setValue:webView.URL.absoluteString forKey:@"url"];
  1188. [parm setValue:@(error.code) forKey:@"errorCode"];
  1189. [parm setValue:error.description forKey:@"errorDesc"];
  1190. [parm setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"version"];
  1191. NSString *content = [parm mj_JSONString];
  1192. NSMutableDictionary *uploadParm = [KSLogManager generateLogMessageWithContent:content type:@"ERROR"];
  1193. NSMutableArray *uploadArray = [NSMutableArray arrayWithObject:uploadParm];
  1194. [KSNetworkingManager sysExceptionLogUpdate:KS_POST token:UserDefault(TokenKey) logArray:uploadArray success:^(NSDictionary * _Nonnull dic) {
  1195. if ([dic ks_integerValueForKey:@"code"] == 200) {
  1196. }
  1197. } faliure:^(NSError * _Nonnull error) {
  1198. }];
  1199. }
  1200. }
  1201. }
  1202. - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
  1203. {
  1204. dispatch_queue_t queue = dispatch_queue_create("webViewChallengeQueue", NULL);
  1205. dispatch_async(queue, ^{
  1206. if (SSL_AUTH) {
  1207. NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  1208. NSURLCredential *customCredential = nil;
  1209. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  1210. // 默认信任
  1211. customCredential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  1212. disposition = NSURLSessionAuthChallengeUseCredential;
  1213. }
  1214. else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
  1215. // client authentication
  1216. SecIdentityRef identity = NULL;
  1217. SecTrustRef trust = NULL;
  1218. if ([AuthChallengeManager extractIdentity:&identity andTrust:&trust filePath:CERT_PATH]) {
  1219. SecCertificateRef certificate = NULL;
  1220. SecIdentityCopyCertificate(identity, &certificate);
  1221. const void*certs[] = {certificate};
  1222. CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
  1223. customCredential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
  1224. disposition = NSURLSessionAuthChallengeUseCredential;
  1225. // 释放 CFArrayRef 和 SecCertificateRef
  1226. CFRelease(certArray);
  1227. CFRelease(certificate);
  1228. }
  1229. }
  1230. if (completionHandler) {
  1231. completionHandler(disposition, customCredential);
  1232. }
  1233. }
  1234. else {
  1235. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  1236. if (challenge.previousFailureCount == 0) {
  1237. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  1238. completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
  1239. } else {
  1240. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  1241. }
  1242. }
  1243. else {
  1244. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  1245. }
  1246. }
  1247. });
  1248. }
  1249. //当因为某些问题,导致webView进程终止时触发
  1250. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
  1251. NSLog(@"%s", __func__);
  1252. if (self.navigationController.visibleViewController == self) {
  1253. [webView reload];
  1254. }
  1255. else {
  1256. self.needReload = YES;
  1257. }
  1258. }
  1259. /**
  1260. * web界面中有弹出警告框时调用
  1261. *
  1262. * @param webView 实现该代理的webview
  1263. * @param message 警告框中的内容
  1264. * @param completionHandler 警告框消失调用
  1265. */
  1266. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
  1267. NSLog(@"-------web界面中有弹出警告框时调用");
  1268. NSLog(@"%@",message);
  1269. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  1270. message:nil
  1271. preferredStyle:UIAlertControllerStyleAlert];
  1272. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  1273. style:UIAlertActionStyleCancel
  1274. handler:^(UIAlertAction *action) {
  1275. completionHandler();
  1276. }]];
  1277. [self presentViewController:alertController animated:YES completion:nil];
  1278. }
  1279. // 取消和确认的按钮
  1280. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
  1281. // js 里面的alert实现,如果不实现,网页的alert函数无效 ,
  1282. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  1283. message:nil
  1284. preferredStyle:UIAlertControllerStyleAlert];
  1285. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  1286. style:UIAlertActionStyleDefault
  1287. handler:^(UIAlertAction *action) {
  1288. completionHandler(YES);
  1289. }]];
  1290. [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
  1291. style:UIAlertActionStyleCancel
  1292. handler:^(UIAlertAction *action){
  1293. completionHandler(NO);
  1294. }]];
  1295. [self presentViewController:alertController animated:YES completion:^{}];
  1296. }
  1297. #pragma mark - KVO回馈
  1298. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  1299. if ([keyPath isEqualToString:@"estimatedProgress"]) {
  1300. self.progressLayer.opacity = 1;
  1301. if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
  1302. return;
  1303. }
  1304. self.progressLayer.frame = CGRectMake(0, 0, kScreenWidth*[change[@"new"] floatValue], 3);
  1305. if ([change[@"new"]floatValue] == 1.0) {
  1306. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1307. self.progressLayer.opacity = 0;
  1308. self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
  1309. });
  1310. }
  1311. }
  1312. }
  1313. /*
  1314. #pragma mark - Navigation
  1315. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1316. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1317. // Get the new view controller using [segue destinationViewController].
  1318. // Pass the selected object to the new view controller.
  1319. }
  1320. */
  1321. - (void)configLocalStorage {
  1322. _hasModify = YES;
  1323. if (![NSString isEmptyString:UserDefault(TokenKey)]) {
  1324. NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('Authorization', '%@ %@')",UserDefault(Token_type), UserDefault(TokenKey)];
  1325. [self.myWebView evaluateJavaScript:jsString completionHandler:nil];
  1326. }
  1327. }
  1328. - (void)setupProgress {
  1329. UIView *progress = [[UIView alloc]init];
  1330. progress.frame = CGRectMake(0, 0, kScreenWidth, 3);
  1331. progress.backgroundColor = [UIColor clearColor];
  1332. [self.view addSubview:progress];
  1333. CALayer *layer = [CALayer layer];
  1334. layer.frame = CGRectMake(0, 0, 0, 3);
  1335. layer.backgroundColor = CLIENT_THEMECOLOR.CGColor;
  1336. [progress.layer addSublayer:layer];
  1337. self.progressLayer = layer;
  1338. }
  1339. + (WKProcessPool*)singleWkProcessPool {
  1340. static WKProcessPool *sharedPool;
  1341. static dispatch_once_t onceToken;
  1342. dispatch_once(&onceToken, ^{
  1343. sharedPool = [[WKProcessPool alloc] init];
  1344. });
  1345. return sharedPool;
  1346. }
  1347. - (NSDictionary *)convertJsonStringToNSDictionary:(NSString *)jsonString {
  1348. if (jsonString == nil) {
  1349. return nil;
  1350. }
  1351. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  1352. NSError *error;
  1353. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
  1354. if (error) {
  1355. NSLog(@"jsonString解析失败:%@", error);
  1356. return nil;
  1357. }
  1358. return json;
  1359. }
  1360. - (void)dealloc {
  1361. NSLog(@"webView dealloc -----");
  1362. [[_myWebView configuration].userContentController removeScriptMessageHandlerForName:SCRIPT_NAME];
  1363. [_myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
  1364. [_myWebView removeObserver:self forKeyPath:@"title"];
  1365. [_myWebView loadHTMLString:@"" baseURL:nil];
  1366. [_myWebView removeFromSuperview];
  1367. _myWebView = nil;
  1368. [self clearWebCache];
  1369. // [[NSURLCache sharedURLCache] removeAllCachedResponses];
  1370. // [[NSURLCache sharedURLCache] setDiskCapacity:0];
  1371. [[NSURLCache sharedURLCache] setMemoryCapacity:0];
  1372. [[NSNotificationCenter defaultCenter] removeObserver:self];
  1373. }
  1374. - (void)clearWebCache {
  1375. NSSet *websiteDataTypes = [NSSet setWithArray:@[
  1376. WKWebsiteDataTypeMemoryCache,
  1377. ]];
  1378. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  1379. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes
  1380. modifiedSince:dateFrom
  1381. completionHandler:^{
  1382. NSLog(@"Caches cleared");
  1383. }];
  1384. }
  1385. - (NSString *)getSaveSpeedPath {
  1386. // 在Documents目录下创建一个名为AudioSpeedFile的文件夹
  1387. NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioSpeedFile"];
  1388. NSLog(@"%@",path);
  1389. NSFileManager *fileManager = [NSFileManager defaultManager];
  1390. BOOL isDir = FALSE;
  1391. BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
  1392. if(!(isDirExist && isDir)) {
  1393. BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  1394. if(!bCreateDir){
  1395. NSLog(@"创建文件夹失败!");
  1396. }
  1397. NSLog(@"创建文件夹成功,文件路径%@",path);
  1398. }
  1399. path = [path stringByAppendingPathComponent:@"songSpeed.plist"];
  1400. NSLog(@"file path:%@",path);
  1401. return path;
  1402. }
  1403. #pragma mark -- 上传图片
  1404. - (void)hudTipWillShow:(BOOL)willShow{
  1405. if (willShow) {
  1406. [self resignFirstResponder];
  1407. UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
  1408. if (!_HUD) {
  1409. _HUD = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
  1410. _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
  1411. _HUD.label.attributedText = [self getAttrStringWithText:@"正在上传视频文件..."];
  1412. _HUD.contentColor = [UIColor whiteColor];
  1413. _HUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
  1414. _HUD.bezelView.backgroundColor = HexRGBAlpha(0x000000, 0.8);
  1415. _HUD.removeFromSuperViewOnHide = YES;
  1416. }else{
  1417. _HUD.progress = 0;
  1418. [keyWindow addSubview:_HUD];
  1419. [_HUD showAnimated:YES];
  1420. }
  1421. }else{
  1422. [_HUD hideAnimated:YES];
  1423. }
  1424. }
  1425. - (NSMutableAttributedString *)getAttrStringWithText:(NSString *)text {
  1426. if (![NSString isEmptyString:text]) {
  1427. NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  1428. [paragraphStyle setLineSpacing:6];//调整行间距
  1429. NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSParagraphStyleAttributeName:paragraphStyle,NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:HexRGB(0xffffff)}];
  1430. return attr;
  1431. }
  1432. else {
  1433. return [[NSMutableAttributedString alloc] initWithString:@""];
  1434. }
  1435. }
  1436. - (void)uploadImageArray:(NSMutableArray *)imageArray bucket:(NSString *)bucket {
  1437. [LOADING_MANAGER showHUD];
  1438. NSMutableArray *imageDataArray = [NSMutableArray array];
  1439. for (UIImage *image in imageArray) {
  1440. NSData *imgData = [UIImage turnsImaegDataByImage:image];
  1441. [imageDataArray addObject:imgData];
  1442. }
  1443. [UPLOAD_MANAGER configWithfilePath:@"/user/"];
  1444. [UPLOAD_MANAGER mutilUploadImage:imageDataArray fileName:@"complainImg" successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1445. [LOADING_MANAGER removeHUD];
  1446. NSMutableArray *urlArray = [NSMutableArray array];
  1447. for (NSString *url in fileUrlArray) {
  1448. [urlArray addObject:url];
  1449. }
  1450. NSString *attachments = [urlArray componentsJoinedByString:@","];
  1451. if (self.chooseFileParm) { // 回调
  1452. [self.chooseFileParm setValue:attachments forKey:@"fileUrl"];
  1453. [self postMessage:self.chooseFileParm];
  1454. self.chooseFileParm = nil;
  1455. }
  1456. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1457. [LOADING_MANAGER removeHUD];
  1458. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1459. [self fileChooseErrorCallback];
  1460. }];
  1461. }
  1462. #pragma mark --- 上传视频文件
  1463. - (void)uploadVideoWithUrl:(NSString *)videoUrl bucket:(NSString *)bucket {
  1464. // 取出视频第一帧
  1465. UIImage *previewImage = [self firstFrameWithVideoURL:[NSURL fileURLWithPath:videoUrl] size:CGSizeMake(1280, 720)];
  1466. __block NSString *imageUrl = @"";
  1467. if (previewImage) { // 如果有第一帧
  1468. NSData *imgData = [UIImage turnsImaegDataByImage:previewImage];
  1469. NSString *fileName = @"videoPreviewImg";
  1470. [UPLOAD_MANAGER configWithfilePath:@"/user/"];
  1471. [UPLOAD_MANAGER uploadImage:imgData fileName:fileName successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1472. NSString *url = [fileUrlArray lastObject];
  1473. imageUrl = url;
  1474. [self submitUrlWith:imageUrl videoUrl:videoUrl];
  1475. } faliure:^(NSError * _Nullable error, NSString *descMessaeg) {
  1476. if (![NSString isEmptyString:descMessaeg]) {
  1477. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1478. }
  1479. [self fileChooseErrorCallback];
  1480. }];
  1481. }
  1482. else {
  1483. [self submitUrlWith:nil videoUrl:videoUrl];
  1484. }
  1485. }
  1486. - (void)submitUrlWith:(NSString *)imgUrl videoUrl:(NSString *)videoUrl {
  1487. // 上传视频
  1488. [self hudTipWillShow:YES];
  1489. NSURL *uploadFileUrl = [NSURL fileURLWithPath:videoUrl];
  1490. NSData *fileData = [NSData dataWithContentsOfURL:uploadFileUrl];
  1491. NSString *suffix = [NSString stringWithFormat:@".%@",[uploadFileUrl pathExtension]];
  1492. [UPLOAD_MANAGER videoUpload:fileData fileName:@"video" fileSuffix:suffix progress:^(int64_t bytesWritten, int64_t totalBytes) {
  1493. dispatch_main_async_safe(^{
  1494. // 显示进度
  1495. if (self.HUD) {
  1496. self.HUD.progress = bytesWritten / totalBytes;// progress是回调进度
  1497. }
  1498. });
  1499. } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1500. [self hudTipWillShow:NO];
  1501. NSString *fileUrl = [fileUrlArray lastObject];
  1502. [self videoUploadCallback:fileUrl firstFrameImg:imgUrl];
  1503. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1504. [self hudTipWillShow:NO];
  1505. if (![NSString isEmptyString:descMessaeg]) {
  1506. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1507. }
  1508. [self videoUploadCallback:@"" firstFrameImg:@""];
  1509. }];
  1510. }
  1511. - (void)videoUploadCallback:(NSString *)remoteVideoUrl firstFrameImg:(NSString *)imgUrl {
  1512. if (self.chooseFileParm) { // 回调
  1513. [self.chooseFileParm setValue:remoteVideoUrl forKey:@"fileUrl"];
  1514. [self.chooseFileParm setValue:imgUrl forKey:@"firstFrameImg"];
  1515. [self postMessage:self.chooseFileParm];
  1516. self.chooseFileParm = nil;
  1517. }
  1518. }
  1519. #pragma mark ---- 获取图片第一帧
  1520. - (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
  1521. {
  1522. // 获取视频第一帧
  1523. NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
  1524. AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
  1525. AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
  1526. generator.appliesPreferredTrackTransform = YES;
  1527. generator.maximumSize = CGSizeMake(size.width, size.height);
  1528. NSError *error = nil;
  1529. CGImageRef imgRef = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
  1530. if (imgRef) {
  1531. UIImage *image = [UIImage imageWithCGImage:imgRef];
  1532. CGImageRelease(imgRef);
  1533. return image;
  1534. }
  1535. else {
  1536. return nil;
  1537. }
  1538. }
  1539. #pragma mark ---- UIDocumentPickerDelegate
  1540. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
  1541. if (self.isDownloadFile) {
  1542. self.isDownloadFile = NO;
  1543. if (self.downloadParm) {
  1544. [self downloadCallback:NO withParm:self.downloadParm];
  1545. self.downloadParm = nil;
  1546. }
  1547. }
  1548. else {
  1549. [self fileChooseErrorCallback];
  1550. }
  1551. }
  1552. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
  1553. if (self.isDownloadFile) {
  1554. self.isDownloadFile = NO;
  1555. [self downloadCallback:YES withParm:self.downloadParm];
  1556. self.downloadParm = nil;
  1557. NSURL *descUrl = [urls firstObject];
  1558. NSString *desc = [descUrl absoluteString];
  1559. KSDocumentViewController *ctrl = (KSDocumentViewController *)controller;
  1560. if (ctrl.currentType == KSDOCUMENT_TYPE_DOWNLOADAUDIO) {
  1561. KSAudioSaveAlert *alert = [KSAudioSaveAlert shareInstance];
  1562. [alert configWithDesc:desc];
  1563. [alert actionCallbackCancel:^{
  1564. } copyCallback:^{
  1565. [self copyAction:desc];
  1566. } sure:^{
  1567. [self openFileSource:descUrl];
  1568. }];
  1569. [alert showAlert];
  1570. }
  1571. else {
  1572. NSLog(@"@------- %zd",[UserDefaultObjectForKey(TENANT_ID) integerValue]);
  1573. if ([UserDefaultObjectForKey(TENANT_ID) integerValue] > 0) { // 机构
  1574. KSSourceDownloadAlert *alertView = [KSSourceDownloadAlert shareInstance];
  1575. [alertView configWithDesc:desc];
  1576. [alertView actionCallbackCancel:^{
  1577. } copyCallback:^{
  1578. [self copyAction:desc];
  1579. } sure:^{
  1580. [self openFileSource:descUrl];
  1581. }];
  1582. [alertView showAlert];
  1583. }
  1584. else {
  1585. KSPlatformDownloadAlert *alertView = [KSPlatformDownloadAlert shareInstance];
  1586. [alertView configWithDesc:desc];
  1587. [alertView actionCallbackCancel:^{
  1588. } copyCallback:^{
  1589. [self copyAction:desc];
  1590. } sure:^{
  1591. [self openFileSource:descUrl];
  1592. }];
  1593. [alertView showAlert];
  1594. }
  1595. }
  1596. }
  1597. else {
  1598. NSURL *url = [urls lastObject];
  1599. NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
  1600. NSString *fileName = [array lastObject];
  1601. fileName = [fileName stringByRemovingPercentEncoding];
  1602. if (self.fileChooseType == CHOOSETYPE_XML) {
  1603. if (![fileName hasSuffix:@".xml"]) {
  1604. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传XML格式文件"];
  1605. [self fileChooseErrorCallback];
  1606. return;
  1607. }
  1608. }
  1609. else if (self.fileChooseType == CHOOSETYPE_MIDI) {
  1610. if (![fileName hasSuffix:@".mid"] || [fileName hasSuffix:@".midi"]) {
  1611. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传mid格式文件"];
  1612. [self fileChooseErrorCallback];
  1613. return;
  1614. }
  1615. }
  1616. else if (self.fileChooseType == CHOOSETYPE_MP3) {
  1617. if (![fileName hasSuffix:@".mp3"]) {
  1618. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传mp3格式文件"];
  1619. [self fileChooseErrorCallback];
  1620. return;
  1621. }
  1622. }
  1623. else {
  1624. if (![fileName hasSuffix:@".mp3"] && ![fileName hasSuffix:@".aac"]) {
  1625. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"暂不支持此格式!"];
  1626. [self fileChooseErrorCallback];
  1627. return;
  1628. }
  1629. }
  1630. __block NSString * fileUrl = @"";
  1631. if ([KSICloudManager iCloudEnable]) {
  1632. [KSICloudManager downloadWithDocumentURL:url callBack:^(id obj) {
  1633. NSData *data = obj;
  1634. //写入沙盒Documents
  1635. NSString *pathStr = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",fileName]];
  1636. [data writeToFile:pathStr atomically:YES];
  1637. if (![[NSFileManager defaultManager] fileExistsAtPath:pathStr]) {
  1638. BOOL isSuccess = [data writeToFile:pathStr atomically:YES];
  1639. if (isSuccess) {
  1640. fileUrl = pathStr;
  1641. }
  1642. else {
  1643. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"写入文件错误!"];
  1644. [self fileChooseErrorCallback];
  1645. }
  1646. }
  1647. else {
  1648. fileUrl = pathStr;
  1649. }
  1650. [self uploadFile:fileName fileUrl:pathStr];
  1651. }];
  1652. }
  1653. else {
  1654. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"iCloud不可用!"];
  1655. [self fileChooseErrorCallback];
  1656. }
  1657. }
  1658. }
  1659. - (void)openFileSource:(NSURL *)path {
  1660. if (self.downloadFileUrl) {
  1661. [self displayFileWithUrl:path];
  1662. }
  1663. else {
  1664. // 开始访问权限
  1665. BOOL fileUrlAuthozied = [path startAccessingSecurityScopedResource];
  1666. if (fileUrlAuthozied) {
  1667. // 通过 NSFileCoordinator 来协调读取
  1668. NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
  1669. NSError *error = nil;
  1670. [fileCoordinator coordinateReadingItemAtURL:path options:0 error:&error byAccessor:^(NSURL *newURL) {
  1671. // 打开文档
  1672. [self displayFileWithUrl:newURL];
  1673. }];
  1674. // 释放权限
  1675. [path stopAccessingSecurityScopedResource];
  1676. } else {
  1677. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"无法访问文件"];
  1678. }
  1679. }
  1680. }
  1681. - (void)displayFileWithUrl:(NSURL *)url {
  1682. // 打开文档
  1683. self.documentVC = [UIDocumentInteractionController interactionControllerWithURL:url];
  1684. // 2. 设置代理(如果需要处理特定交互事件)
  1685. self.documentVC.delegate = self;
  1686. // 3. 显示“打开方式”菜单或文件预览
  1687. // 从指定的视图呈现操作菜单
  1688. [self.documentVC presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
  1689. }
  1690. - (void)copyAction:(NSString *)desc {
  1691. // 复制
  1692. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1693. pasteboard.string = [NSString returnNoNullStringWithString:desc];
  1694. [LOADING_MANAGER MBShowAUTOHidingInWindow:@"复制成功"];
  1695. }
  1696. - (void)fileChooseErrorCallback {
  1697. if (self.chooseFileParm) { // 回调
  1698. [self.chooseFileParm setValue:@"" forKey:@"fileUrl"];
  1699. [self postMessage:self.chooseFileParm];
  1700. self.chooseFileParm = nil;
  1701. }
  1702. }
  1703. - (void)uploadFile:(NSString *)fileName fileUrl:(NSString *)fileUrl {
  1704. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1705. [LOADING_MANAGER showHUD];
  1706. NSString *suffix = [NSString stringWithFormat:@".%@",[[fileName componentsSeparatedByString:@"."] lastObject]];
  1707. NSData *fileData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:fileUrl]];
  1708. [UPLOAD_MANAGER configWithfilePath:@"/user/"];
  1709. [UPLOAD_MANAGER uploadFile:fileData fileName:@"file" fileSuffix:suffix progress:^(int64_t bytesWritten, int64_t totalBytes) {
  1710. int progress = (int)(bytesWritten / totalBytes * 100);
  1711. __block NSString *tipsMessage = [NSString stringWithFormat:@"上传中 %d%%",progress];
  1712. dispatch_main_async_safe(^{
  1713. [LOADING_MANAGER.loadingView setDisplayText:tipsMessage];
  1714. });
  1715. } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1716. [LOADING_MANAGER removeHUD];
  1717. NSString *fileUrl = [fileUrlArray lastObject];
  1718. if (self.chooseFileParm) { // 回调
  1719. [self.chooseFileParm setValue:fileUrl forKey:@"fileUrl"];
  1720. [self postMessage:self.chooseFileParm];
  1721. self.chooseFileParm = nil;
  1722. }
  1723. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1724. [LOADING_MANAGER removeHUD];
  1725. [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
  1726. [self fileChooseErrorCallback];
  1727. }];
  1728. });
  1729. }
  1730. - (CGFloat)getFileSize:(NSURL *)fileUrl {
  1731. NSFileManager *fileManager = [NSFileManager defaultManager];
  1732. float filesize = -1.0;
  1733. NSString *path = fileUrl.path;
  1734. if ([fileManager fileExistsAtPath:path]) {
  1735. NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
  1736. unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
  1737. filesize = 1.0*size/1024/1024;
  1738. }
  1739. return filesize;
  1740. }
  1741. #pragma mark - UIDocumentInteractionControllerDelegate
  1742. -(UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller{
  1743. return self;
  1744. }
  1745. -(UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {
  1746. return self.view;
  1747. }
  1748. -(CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
  1749. return self.view.frame;
  1750. }
  1751. #pragma mark ---- 镜像和投屏检测
  1752. - (void)captureViewTips:(NSNotification *)notification {
  1753. [self checkCaptured];
  1754. }
  1755. - (void)checkCaptured {
  1756. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1757. if ([self checkIsCaptured]) {
  1758. [self didCapturedView];
  1759. }
  1760. });
  1761. }
  1762. - (BOOL)checkIsCaptured {
  1763. if ([UIScreen mainScreen].isCaptured && [UIScreen screens].count < 2) {
  1764. return YES;
  1765. }
  1766. return NO;
  1767. }
  1768. - (void)didCapturedView {
  1769. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  1770. [sendParm setValue:@"setVideoPlayer" forKey:@"api"];
  1771. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  1772. [content setValue:@"pause" forKey:@"status"];
  1773. [sendParm setValue:content forKey:@"content"];
  1774. [self postMessage:sendParm];
  1775. }
  1776. - (KSWebLoadRefreshView *)errorView {
  1777. if (!_errorView) {
  1778. _errorView = [KSWebLoadRefreshView shareInstance];
  1779. MJWeakSelf;
  1780. [_errorView failViewActionCallback:^(BOOL isBack) {
  1781. [weakSelf hideErrorView];
  1782. if (isBack) {
  1783. [weakSelf backAction];
  1784. }
  1785. else {
  1786. [weakSelf loadRequest];
  1787. }
  1788. }];
  1789. }
  1790. return _errorView;
  1791. }
  1792. - (void)showErrorView {
  1793. if (![self.view.subviews containsObject:self.errorView]) {
  1794. [self.view addSubview:self.errorView];
  1795. [self.errorView mas_makeConstraints:^(MASConstraintMaker *make) {
  1796. make.left.right.top.bottom.mas_equalTo(self.view);
  1797. }];
  1798. [self.view bringSubviewToFront:self.errorView];
  1799. }
  1800. }
  1801. - (void)hideErrorView {
  1802. if ([self.view.subviews containsObject:self.errorView]) {
  1803. [self.errorView removeFromSuperview];
  1804. }
  1805. }
  1806. #pragma mark ----- 小酷AI loading
  1807. - (AccompanyLoadingView *)customLoading {
  1808. if (!_customLoading) {
  1809. _customLoading = [AccompanyLoadingView shareInstance];
  1810. MJWeakSelf;
  1811. [_customLoading loadingCallback:^{
  1812. [weakSelf backAction];
  1813. }];
  1814. }
  1815. return _customLoading;
  1816. }
  1817. - (void)showCustomLoading {
  1818. if ([self.view.subviews containsObject:self.customLoading]) {
  1819. return;
  1820. }
  1821. [self.view addSubview:self.customLoading];
  1822. [self.customLoading mas_makeConstraints:^(MASConstraintMaker *make) {
  1823. make.left.top.right.bottom.mas_equalTo(self.view);
  1824. }];
  1825. [self.view bringSubviewToFront:self.customLoading];
  1826. [self.customLoading showLoading];
  1827. }
  1828. - (void)removeCustomLoadingView {
  1829. [self.customLoading stopLoading];
  1830. }
  1831. /*
  1832. #pragma mark - Navigation
  1833. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1834. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1835. // Get the new view controller using [segue destinationViewController].
  1836. // Pass the selected object to the new view controller.
  1837. }
  1838. */
  1839. @end