KSBaseWKWebViewController.m 70 KB

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