KSBaseWKWebViewController.m 75 KB

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