KSBaseWKWebViewController.m 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. //
  2. // KSBaseWKWebViewController.m
  3. // KulexiuForTeacher
  4. //
  5. // Created by Kyle on 2022/3/17.
  6. //
  7. #import "KSBaseWKWebViewController.h"
  8. #import "JPUSHService.h"
  9. #import "LoginViewController.h"
  10. #import "AppDelegate.h"
  11. #import "CustomNavViewController.h"
  12. #import <RongIMKit/RongIMKit.h>
  13. #import "UIDevice+TFDevice.h"
  14. #import "KSPremissionAlert.h"
  15. #import "RecordCheckManager.h"
  16. #import "KSLocalWebViewController.h"
  17. #import "RCConnectionManager.h"
  18. #import "KSAccompanyWebViewController.h"
  19. #import "KSChatConversationViewController.h"
  20. #import "KSMediaManager.h"
  21. #import <AVFoundation/AVFoundation.h>
  22. #import "KSDocumentViewController.h"
  23. #import "KSICloudManager.h"
  24. #import "AddressListViewController.h"
  25. #import "KSOrderManager.h"
  26. #import "KSEnterLiveroomManager.h"
  27. typedef NS_ENUM(NSInteger, CHOOSETYPE) {
  28. CHOOSETYPE_XML,
  29. CHOOSETYPE_MIDI,
  30. CHOOSETYPE_MP3,
  31. CHOOSETYPE_ALL,
  32. };
  33. @interface KSBaseWKWebViewController ()<UIDocumentPickerDelegate>
  34. @property (nonatomic, assign) BOOL isOutLink; // 外部链接
  35. @property (nonatomic,weak) CALayer *progressLayer;
  36. @property (nonatomic, strong) NSString *currerntURL; // 当前web URL
  37. @property (nonatomic, assign) BOOL hasModify;
  38. @property (nonatomic, assign) BOOL hasChangeSource; // 是否切换了亮屏,横屏等配置
  39. @property (nonatomic, assign) BOOL landScape;
  40. /// 选择本地文件 parm
  41. @property (nonatomic, strong) NSMutableDictionary *chooseFileParm;
  42. @property (nonatomic, strong) KSMediaManager *mediaManager;
  43. @property (strong, nonatomic) MBProgressHUD *HUD;
  44. @property (nonatomic, assign) CHOOSETYPE fileChooseType;
  45. @end
  46. @implementation KSBaseWKWebViewController
  47. - (void)viewDidLoad {
  48. [super viewDidLoad];
  49. // Do any additional setup after loading the view.
  50. self.ks_prefersNavigationBarHidden = YES; // 隐藏导航栏,其他事件额外处理
  51. [self initWebView];
  52. }
  53. - (void)setParmDic:(NSDictionary *)parmDic {
  54. _parmDic = parmDic;
  55. _hasChangeSource = YES;
  56. BOOL isOpenLight = [parmDic boolValueForKey:@"isOpenLight"];
  57. [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
  58. // 横竖屏
  59. NSInteger orientation = [parmDic integerValueForKey:@"orientation"];
  60. BOOL isLandScape = orientation == 0 ? YES : NO;
  61. if (_landScape != isLandScape) {
  62. [self changeOrientation:isLandScape];
  63. }
  64. // 是否隐藏头部导航条
  65. self.hideTop = [parmDic boolValueForKey:@"isHideTitle"];
  66. }
  67. - (void)changeOrientation:(BOOL)isLandScape {
  68. self.landScape = isLandScape;
  69. if (isLandScape) {
  70. // 切换到横屏
  71. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  72. delegate.allowAutoRotate = YES;
  73. [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
  74. }
  75. else {
  76. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  77. delegate.allowAutoRotate = NO;
  78. [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
  79. }
  80. }
  81. - (void)viewWillAppear:(BOOL)animated {
  82. [super viewWillAppear:animated];
  83. if (_hasChangeSource) {
  84. [self setParmDic:self.parmDic];
  85. }
  86. }
  87. - (void)viewWillDisappear:(BOOL)animated {
  88. [super viewWillDisappear:animated];
  89. if (_hasChangeSource && self.keepOrientation == NO && self.landScape == YES) {
  90. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  91. [self changeOrientation:NO];
  92. }
  93. self.keepOrientation = NO;
  94. }
  95. - (void)initWebView {
  96. [self.view addSubview:self.navView];
  97. CGFloat topHeight = kNaviBarHeight;
  98. if (self.hideTop) {
  99. topHeight = 0.0f;
  100. }
  101. [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
  102. make.left.right.top.mas_equalTo(self.view);
  103. make.height.mas_equalTo(topHeight);
  104. }];
  105. [self.view addSubview:self.webBackButton];
  106. [self.webBackButton mas_makeConstraints:^(MASConstraintMaker *make) {
  107. make.left.top.mas_equalTo(self.view);
  108. make.height.mas_equalTo(kNaviBarHeight);
  109. make.width.mas_equalTo(44);
  110. }];
  111. if (self.hideTop) {
  112. self.webBackButton.hidden = YES;
  113. }
  114. if (_hiddenNavBar) {
  115. topHeight = 0.0f;
  116. }
  117. if (self.headTitle) {
  118. [self.navView.topTitleLabel setText:_headTitle];
  119. }
  120. if (_myWebView == nil) {
  121. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  122. config.selectionGranularity = WKSelectionGranularityDynamic;
  123. config.allowsInlineMediaPlayback = YES;
  124. if (@available(iOS 10.0, *)) {
  125. config.mediaTypesRequiringUserActionForPlayback = NO;
  126. } else {
  127. // Fallback on earlier versions
  128. config.requiresUserActionForMediaPlayback = NO;
  129. }
  130. config.processPool = [KSBaseWKWebViewController singleWkProcessPool];
  131. config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  132. //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
  133. WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
  134. //这个类主要用来做native与JavaScript的交互管理
  135. WKUserContentController * wkUController = [[WKUserContentController alloc] init];
  136. [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"COLEXIU"];
  137. config.userContentController = wkUController;
  138. WKPreferences *preferences = [WKPreferences new];
  139. // 是否支出javaScript
  140. preferences.javaScriptEnabled = YES;
  141. //不通过用户交互,是否可以打开窗口
  142. preferences.javaScriptCanOpenWindowsAutomatically = YES;
  143. config.preferences = preferences;
  144. _myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
  145. _myWebView.UIDelegate = self;
  146. _myWebView.navigationDelegate = self;
  147. _myWebView.scrollView.bounces = NO;
  148. // 加载进度条和title
  149. [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  150. [_myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
  151. [self.view addSubview:_myWebView];
  152. [_myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
  153. make.left.right.mas_equalTo(self.view);
  154. make.top.mas_equalTo(self.view.mas_top).offset(topHeight);
  155. make.bottom.mas_equalTo(self.view.mas_bottom).offset(-iPhoneXSafeBottomMargin);
  156. }];
  157. if (@available(iOS 11.0, *)) {
  158. _myWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  159. } else {
  160. // Fallback on earlier versions
  161. }
  162. [self setupProgress];
  163. // 修改userAgent
  164. [self setUserAgent];
  165. [self.view bringSubviewToFront:self.navView];
  166. [self.view bringSubviewToFront:self.webBackButton];
  167. }
  168. else {
  169. [_myWebView reload];
  170. }
  171. }
  172. - (void)setUserAgent {
  173. MJWeakSelf;
  174. [self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
  175. NSString *oldUserAgent = result;
  176. NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@",oldUserAgent,@"COLEXIUAPPI"];
  177. weakSelf.myWebView.customUserAgent = newUserAgent;
  178. [weakSelf loadRequest];;
  179. }];
  180. }
  181. - (void)loadRequest {
  182. MJWeakSelf;
  183. [self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
  184. NSLog(@"%@",result);
  185. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:weakSelf.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  186. [weakSelf.myWebView loadRequest:request];
  187. }];
  188. }
  189. - (NSString *)url {
  190. if (_url) {
  191. if ([_url containsString:@"Authorization="]) {
  192. NSRange range = [_url rangeOfString:@"Authorization="];
  193. if (range.location != NSNotFound) {
  194. _url = [_url substringToIndex:range.location-1];
  195. }
  196. }
  197. NSString *sepectString = [_url containsString:@"?"] ? @"&" : @"?";
  198. NSString *tokenStr = UserDefault(TokenKey);
  199. if (![NSString isEmptyString:tokenStr]) {
  200. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  201. _url = [NSString stringWithFormat:@"%@%@%@",_url, sepectString, token];
  202. }
  203. }
  204. return _url;
  205. }
  206. #pragma mark --- 返回按钮的处理
  207. - (void)backAction {
  208. [self.myWebView stopLoading];
  209. if (_backRootView) {
  210. [self.navigationController popToRootViewControllerAnimated:NO];
  211. return;
  212. }
  213. else if (_isBackPreView) {
  214. [self.navigationController popViewControllerAnimated:YES];
  215. return;
  216. }
  217. else if ([self.myWebView canGoBack]) {
  218. [self.myWebView goBack];
  219. }
  220. else {
  221. [self.navigationController popViewControllerAnimated:YES];
  222. }
  223. }
  224. #pragma mark - WKScriptMessageHandler
  225. - (void)userContentController:(WKUserContentController *)userContentController
  226. didReceiveScriptMessage:(WKScriptMessage *)message {
  227. if ([message.name isEqualToString:@"COLEXIU"]) {
  228. NSDictionary *parm = [self convertJsonStringToNSDictionary:message.body];
  229. // 回到主线程
  230. dispatch_async(dispatch_get_main_queue(), ^{
  231. [self handleScriptMessageSource:parm];
  232. });
  233. }
  234. }
  235. - (void)handleScriptMessageSource:(NSDictionary *)parm {
  236. if ([[parm stringValueForKey:@"api"] isEqualToString:@"back"]) { // 返回
  237. [self.navigationController popViewControllerAnimated:YES];
  238. }
  239. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"login"]) {
  240. // 回到登录页面
  241. [self backLoginView];
  242. }
  243. // chat
  244. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openConversationActivity"]) {
  245. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  246. NSString *name = [valueDic stringValueForKey:@"name"];
  247. NSString *userId = [NSString stringWithFormat:@"%.0f",[valueDic floatValueForKey:@"userId"]];
  248. KSChatConversationViewController *conversationVC = [[KSChatConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:[NSString returnNoNullStringWithString:userId]];
  249. conversationVC.title = [NSString returnNoNullStringWithString:name];
  250. [self.navigationController pushViewController:conversationVC animated:YES];
  251. }
  252. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openWebView"]) { // 打开新页面
  253. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  254. KSBaseWKWebViewController *detailCtrl = [[KSBaseWKWebViewController alloc] init];
  255. detailCtrl.url = [valueDic stringValueForKey:@"url"];
  256. detailCtrl.parmDic = valueDic;
  257. NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
  258. BOOL isLandScape = orientation == 0 ? YES : NO;
  259. if (isLandScape == self.landScape) {
  260. self.keepOrientation = YES;
  261. detailCtrl.keepOrientation = YES;
  262. }
  263. [self postMessage:parm];
  264. [self.navigationController pushViewController:detailCtrl animated:YES];
  265. }
  266. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"setRequestedOrientation"]) {
  267. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  268. // 横竖屏
  269. NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
  270. BOOL isLandScape = orientation == 0 ? YES : NO;
  271. [self changeOrientation:isLandScape];
  272. }
  273. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"keepScreenLongLight"]) {
  274. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  275. BOOL isOpenLight = [valueDic boolValueForKey:@"isOpenLight"];
  276. [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
  277. }
  278. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"downLoad"]) {
  279. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  280. if ([valueDic stringValueForKey:@"PDF"]) {
  281. NSString *url = [valueDic stringValueForKey:@"downloadUrl"];
  282. [KSNetworkingManager downloadFileRequestWithFileUrl:url progress:^(int64_t bytesRead, int64_t totalBytes) {
  283. } success:^(NSURL * _Nonnull fileUrl) {
  284. MJWeakSelf;
  285. [self KSShowMsg:@"下载成功" promptCompletion:^{
  286. [weakSelf displaySource:fileUrl];
  287. }];
  288. } faliure:^(NSError * _Nonnull error) {
  289. }];
  290. }
  291. }
  292. // 回调是否刘海屏
  293. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"isSpecialShapedScreen"]) {
  294. BOOL isShapedScreen = iPhoneXSafeTopMargin > 0 ? YES : NO;
  295. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm dictionaryValueForKey:@"content"]];
  296. [valueDic setValue:@(isShapedScreen) forKey:@"isSpecialShapedScreen"];
  297. [valueDic setValue:@(iPhoneXSafeTopMargin*2) forKey:@"notchHeight"];
  298. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  299. [sendParm setValue:valueDic forKey:@"content"];
  300. [self postMessage:sendParm];
  301. }
  302. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"getToken"]) {
  303. NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm dictionaryValueForKey:@"content"]];
  304. [valueDic setValue:UserDefault(Token_type) forKey:@"tokenType"];
  305. [valueDic setValue:UserDefault(TokenKey) forKey:@"accessToken"];
  306. NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
  307. [sendParm setValue:valueDic forKey:@"content"];
  308. [self postMessage:sendParm];
  309. }
  310. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openAccompanyWebView"]) { // 打开伴奏
  311. PREMISSIONTYPE micEnable = [RecordCheckManager checkPermissionShowAlert:NO showInView:nil];
  312. PREMISSIONTYPE cameraEnable = [RecordCheckManager checkCameraPremissionAvaiable:NO showInView:nil];
  313. if (micEnable == PREMISSIONTYPE_YES && cameraEnable == PREMISSIONTYPE_YES) { // 如果麦克风和摄像头权限都有
  314. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  315. KSAccompanyWebViewController *detailCtrl = [[KSAccompanyWebViewController alloc] init];
  316. detailCtrl.url = [valueDic stringValueForKey:@"url"];
  317. detailCtrl.parmDic = valueDic;
  318. detailCtrl.hiddenNavBar = [valueDic boolValueForKey:@"isHideTitle"];
  319. NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
  320. BOOL isLandScape = orientation == 0 ? YES : NO;
  321. if (isLandScape == self.landScape) {
  322. self.keepOrientation = YES;
  323. detailCtrl.keepOrientation = YES;
  324. }
  325. [self postMessage:parm];
  326. [self.navigationController pushViewController:detailCtrl animated:YES];
  327. }
  328. else {
  329. if (micEnable == PREMISSIONTYPE_NO && cameraEnable == PREMISSIONTYPE_NO) { // 如果麦克风权限和摄像头权限都没有
  330. [self showAlertWithMessage:@"请开启相机和麦克风访问权限" type:CHECKDEVICETYPE_BOTH];
  331. }
  332. else if (micEnable == PREMISSIONTYPE_NO) { // 如果没有麦克风权限
  333. [self showAlertWithMessage:@"请开启麦克风访问权限" type:CHECKDEVICETYPE_MIC];
  334. }
  335. else if (cameraEnable == PREMISSIONTYPE_NO) { // 如果没有摄像头权限
  336. [self showAlertWithMessage:@"请开启相机访问权限" type:CHECKDEVICETYPE_CAMREA];
  337. }
  338. }
  339. }
  340. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"checkAlbum"]) { // 判断权限
  341. [self postMessage:parm];
  342. PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable:NO showInView:nil];
  343. if (albumEnable == PREMISSIONTYPE_NO) {
  344. [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
  345. }
  346. }
  347. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"shareAchievements"]) { // 分享
  348. //
  349. [self shareFunctionWithParm:parm];
  350. }
  351. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"getNavHeight"]) { // 获取状态栏高度和 title heigt
  352. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  353. [valueDic setValue:[NSNumber numberWithFloat:STATUS_GAP*2] forKey:@"navHeight"];
  354. [valueDic setValue:@(44*2) forKey:@"titleHeight"];
  355. [parm setValue:valueDic forKey:@"content"];
  356. [self postMessage:parm];
  357. }
  358. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"backIconChange"]) {
  359. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  360. NSString *backColor = [valueDic stringValueForKey:@"iconStyle"];
  361. NSString *backImage = @"";
  362. if ([backColor isEqualToString:@"black"]) {
  363. backImage = @"back_black";
  364. }
  365. else {
  366. backImage = @"back_button_white";
  367. }
  368. [self.webBackButton.backButton setImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
  369. }
  370. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"setBarStatus"]) { // 顶部是否隐藏
  371. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  372. BOOL isShow = [valueDic boolValueForKey:@"status"]; // 0 隐藏 1 显示
  373. self.hiddenNavBar = !isShow;
  374. CGFloat navHeight = isShow ? kNaviBarHeight : 0;
  375. [self.navView mas_updateConstraints:^(MASConstraintMaker *make) {
  376. make.height.mas_equalTo(navHeight);
  377. }];
  378. [self.myWebView mas_updateConstraints:^(MASConstraintMaker *make) {
  379. make.top.mas_equalTo(self.view.mas_top).offset(navHeight);
  380. }];
  381. }
  382. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"chooseFile"]) {
  383. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  384. self.chooseFileParm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
  385. NSString *typeStr = [valueDic stringValueForKey:@"type"];
  386. NSInteger maxCount = [valueDic integerValueForKey:@"max"];
  387. [self chooseFileWithType:typeStr maxNumber:maxCount];
  388. }
  389. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"setAddress"]) { // 跳转地址选择
  390. AddressListViewController *ctrl = [[AddressListViewController alloc] init];
  391. ctrl.isChooseAddress = YES;
  392. MJWeakSelf;
  393. [ctrl chooseAddressAction:^(AddressListModel * _Nonnull model) {
  394. [weakSelf sendAddressAction:model];
  395. }];
  396. [self.navigationController pushViewController:ctrl animated:YES];
  397. }
  398. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"paymentOrder"]) {
  399. NSDictionary *content = [parm dictionaryValueForKey:@"content"];
  400. NSString *channel = [content stringValueForKey:@"payChannel"];
  401. if ([channel isEqualToString:@"ali_app"]) {
  402. NSString *infoMessage = [content stringValueForKey:@"payInfo"];
  403. [KSOrderManager dealWithAliSDK:infoMessage];
  404. }
  405. else if ([channel isEqualToString:@"wx_app"]) {
  406. NSString *infoMessage = [content stringValueForKey:@"payInfo"];
  407. [KSOrderManager dealWithWXSDK:infoMessage];
  408. }
  409. }
  410. else if ([[parm stringValueForKey:@"api"] isEqualToString:@"joinLiveRoom"]) { // 进入直播间
  411. NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
  412. NSString *roomId = [valueDic stringValueForKey:@"roomId"];
  413. [self showhud];
  414. [KSEnterLiveroomManager joinLiveWithRoomId:roomId inController:(CustomNavViewController *)self.navigationController callback:^{
  415. [self removehub];
  416. }];
  417. }
  418. }
  419. - (void)sendAddressAction:(AddressListModel *)model {
  420. NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  421. [sendParm setValue:@"getAddress" forKey:@"api"];
  422. NSMutableDictionary *content = [NSMutableDictionary dictionary];
  423. [content setValue:model.internalBaseClassIdentifier forKey:@"id"];
  424. [content setValue:model.detailAddress forKey:@"detailAddress"];
  425. [content setValue:model.city forKey:@"city"];
  426. [content setValue:model.region forKey:@"region"];
  427. [content setValue:model.province forKey:@"province"];
  428. [content setValue:model.name forKey:@"name"];
  429. [content setValue:model.phoneNumber forKey:@"phoneNumber"];
  430. [content setValue:model.postCode forKey:@"postCode"];
  431. [sendParm setValue:content forKey:@"content"];
  432. [self postMessage:sendParm];
  433. }
  434. - (void)chooseFileWithType:(NSString *)typeStr maxNumber:(NSInteger)maxCount {
  435. if ([typeStr isEqualToString:@"img"]) { // 选择图片上传
  436. if (maxCount > 9) {
  437. maxCount = 9;
  438. }
  439. [self chooseMediaWithType:MEDIATYPE_PHOTO maxCount:maxCount];
  440. }
  441. else if ([typeStr isEqualToString:@"video"]) {
  442. [self chooseMediaWithType:MEDIATYPE_VIDEO maxCount:1];
  443. }
  444. else if ([typeStr isEqualToString:@"file"]) {
  445. [self chooseDocumentWithType:CHOOSETYPE_ALL];
  446. }
  447. else if ([typeStr isEqualToString:@"midi"]) {
  448. [self chooseDocumentWithType:CHOOSETYPE_MIDI];
  449. }
  450. else if ([typeStr isEqualToString:@"mp3"]) {
  451. [self chooseDocumentWithType:CHOOSETYPE_MP3];
  452. }
  453. else if ([typeStr isEqualToString:@"xml"]) {
  454. [self chooseDocumentWithType:CHOOSETYPE_XML];
  455. }
  456. }
  457. - (void)chooseDocumentWithType:(CHOOSETYPE)fileTyle {
  458. self.fileChooseType = fileTyle;
  459. 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"];
  460. KSDocumentViewController *documentPickerViewController = [[KSDocumentViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeImport];
  461. documentPickerViewController.delegate = self;
  462. documentPickerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  463. [self presentViewController:documentPickerViewController animated:YES completion:nil];
  464. }
  465. - (void)chooseMediaWithType:(MEDIATYPE)type maxCount:(NSInteger)maxCount {
  466. self.mediaManager = [[KSMediaManager alloc] init];
  467. self.mediaManager.mediaType = type;
  468. self.mediaManager.maxPhotoNumber = maxCount;
  469. self.mediaManager.baseCtrl = self;
  470. self.mediaManager.needCropImage = NO;
  471. self.mediaManager.videoMaxDuration = 40 * 60;
  472. MJWeakSelf;
  473. [self.mediaManager noAlertCallback:^(NSString * _Nullable videoUrl, NSMutableArray * _Nullable imageArray, NSMutableArray * _Nullable imageAsset) {
  474. if (type == MEDIATYPE_PHOTO) {
  475. [self uploadImageArray:imageArray];
  476. }
  477. else {
  478. NSLog(@"%@", videoUrl);
  479. // 上传视频
  480. [weakSelf uploadVideoWithUrl:videoUrl];
  481. }
  482. }];
  483. [self.mediaManager pushImagePickerController];
  484. }
  485. - (UIImage *)imageWithBase64String:(NSString *)base64String {
  486. NSURL *URL = [NSURL URLWithString:base64String];
  487. NSData *imageData = [NSData dataWithContentsOfURL:URL];
  488. UIImage *image = [UIImage imageWithData:imageData scale:2];
  489. return image;
  490. }
  491. - (void)shareFunctionWithParm:(NSDictionary *)parm {
  492. // NSDictionary *content = [parm dictionaryValueForKey:@"content"];
  493. // NSString *typeString = [content stringValueForKey:@"type"];
  494. // KSSHARETYPE shareType = [typeString isEqualToString:@"image"] ? KSSHARETYPE_IMAGE : KSSHARETYPE_VODEO;
  495. // NSString *shareTitle = [content stringValueForKey:@"title"];
  496. // NSString *descMessage = [content stringValueForKey:@"desc"];
  497. // NSString *videoUrl = [content stringValueForKey:@"video"];
  498. // NSString *imgStr = [content stringValueForKey:@"image"];
  499. // UIImage *shareImage = [self imageWithBase64String:imgStr];
  500. // [KSUMShareManager shareInstanceWithImage:shareImage url:videoUrl shareTitle:shareTitle descMessage:descMessage shareType:shareType showInView:self callback:^(BOOL isSuccess, NSString *descMessage) {
  501. // NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
  502. // [responParm setValue:[parm stringValueForKey:@"api"] forKey:@"api"];
  503. // NSMutableDictionary *content = [NSMutableDictionary dictionary];
  504. // [content setValue:[content stringValueForKey:@"UUID"] forKey:@"content"];
  505. // [content setValue:descMessage forKey:@"message"];
  506. // BOOL status = isSuccess;
  507. // [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
  508. // [responParm setValue:content forKey:@"content"];
  509. // [self postMessage:responParm];
  510. // }];
  511. }
  512. - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
  513. [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
  514. } confirm:^{
  515. [self openSettingView];
  516. }];
  517. }
  518. - (void)openSettingView {
  519. if (@available(iOS 10, *)) {
  520. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
  521. } else {
  522. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  523. }
  524. }
  525. - (void)displaySource:(NSURL *)localUrl {
  526. KSLocalWebViewController *ctrl = [[KSLocalWebViewController alloc] init];
  527. ctrl.headTitle = @"协议文件";
  528. ctrl.sourceData = [NSData dataWithContentsOfURL:localUrl];
  529. ctrl.fileUrl = localUrl;
  530. [self.navigationController pushViewController:ctrl animated:YES];
  531. }
  532. - (void)postMessage:(NSDictionary *)parm {
  533. if (_myWebView) {
  534. dispatch_async(dispatch_get_main_queue(), ^{
  535. NSString *jsString = [parm mj_JSONString];
  536. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"postMessage(%@,'*')", jsString] completionHandler:nil];
  537. });
  538. }
  539. }
  540. // 刷新
  541. - (void)refreshUrl:(NSString *)refreshUrl {
  542. NSString *sepectString = [refreshUrl containsString:@"?"] ? @"&" : @"?";
  543. NSString *tokenStr = UserDefault(TokenKey);
  544. if (![NSString isEmptyString:tokenStr]) {
  545. NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  546. refreshUrl = [NSString stringWithFormat:@"%@%@%@",refreshUrl, sepectString, token];
  547. }
  548. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:refreshUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
  549. [self.myWebView loadRequest:request];
  550. }
  551. // 返回登录页面
  552. - (void)backLoginView {
  553. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  554. [RCConnectionManager shareManager].isNeedJoin = NO;
  555. [RCConnectionManager shareManager].isNeedShowMessage = NO;
  556. [[RCIM sharedRCIM] logout];
  557. NSString *webUrl = [self.url copy];
  558. if ([webUrl containsString:@"Authorization="]) {
  559. NSRange range = [webUrl rangeOfString:@"Authorization="];
  560. if (range.location != NSNotFound) {
  561. webUrl = [webUrl substringToIndex:range.location-1];
  562. }
  563. }
  564. // 获取次数
  565. NSString *failCount = UserDefault(@"WEB_FAILCOUNT");
  566. if ([NSString isEmptyString:failCount]) {
  567. failCount = @"1";
  568. UserDefaultSetObjectForKey(failCount, @"WEB_FAILCOUNT");
  569. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  570. }
  571. else if (failCount.integerValue == 1) {
  572. NSString *preUrl = UserDefaultObjectForKey(FAIL_WEB_URL);
  573. if (![webUrl isEqualToString:preUrl]) { // 如果打开和之前失败不相同重新统计数据
  574. UserDefaultSetObjectForKey(@"1", @"WEB_FAILCOUNT");
  575. UserDefaultSetObjectForKey(webUrl, WEB_URL);
  576. }
  577. else {
  578. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  579. }
  580. }
  581. else {
  582. UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
  583. }
  584. // 当前失败的H5地址
  585. UserDefaultSetObjectForKey(webUrl, FAIL_WEB_URL);
  586. // 取消推送别名
  587. [JPUSHService deleteAlias:nil seq:0];
  588. [[NSUserDefaults standardUserDefaults] removeObjectForKey:TokenKey];
  589. [[NSUserDefaults standardUserDefaults] removeObjectForKey:Token_type];
  590. [[NSUserDefaults standardUserDefaults] removeObjectForKey:RongTokenKey];
  591. [[NSUserDefaults standardUserDefaults] removeObjectForKey:RefreshToken];
  592. [KSNetworkingManager clearRequestHeader];
  593. LoginViewController *loginVC = [[LoginViewController alloc] init];
  594. CustomNavViewController *navCtrl = [[CustomNavViewController alloc] initWithRootViewController:loginVC];
  595. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  596. appDelegate.window.rootViewController = navCtrl;
  597. }
  598. #pragma mark ----- WKWebView delegate
  599. // 1 在发送请求之前,决定是否跳转
  600. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  601. NSLog(@"1-------在发送请求之前,决定是否跳转 -->%@",navigationAction.request);
  602. NSURL *url = navigationAction.request.URL;
  603. NSString *scheme = [url scheme];
  604. UIApplication *app = [UIApplication sharedApplication];
  605. NSString *urlString = url.absoluteString;
  606. if (![urlString containsString:@"colexiu.com"] && ![urlString containsString:WEBHOST]) { // 外部链接
  607. self.isOutLink = YES;
  608. }
  609. else {
  610. self.isOutLink = NO;
  611. }
  612. // 打电话
  613. if ([scheme isEqualToString:@"tel"]) {
  614. if ([app canOpenURL:url]) {
  615. [app openURL:url];
  616. // 一定要加上这句,否则会打开新页面
  617. decisionHandler(WKNavigationActionPolicyCancel);
  618. return;
  619. }
  620. }
  621. decisionHandler(WKNavigationActionPolicyAllow);
  622. }
  623. // 2 页面开始加载时调用
  624. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  625. NSLog(@"2-------页面开始加载时调用");
  626. }
  627. // 3 在收到响应后,决定是否跳转
  628. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  629. /// 在收到服务器的响应头,根据response相关信息,决定是否跳转。decisionHandler必须调用,来决定是否跳转,参数WKNavigationActionPolicyCancel取消跳转,WKNavigationActionPolicyAllow允许跳转
  630. NSLog(@"3-------在收到响应后,决定是否跳转");
  631. decisionHandler(WKNavigationResponsePolicyAllow);
  632. }
  633. // 4 当内容开始返回时调用
  634. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
  635. NSLog(@"4-------当内容开始返回时调用");
  636. }
  637. // 5 页面加载完成之后调用
  638. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  639. NSLog(@"5-------页面加载完成之后调用");
  640. if (_hasModify == NO) {
  641. [self configLocalStorage];
  642. }
  643. }
  644. // 调用js方法
  645. - (void)postMessageJS:(NSDictionary *)jsDict {
  646. NSString *jsString = [jsDict mj_JSONString];
  647. [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"sendMessage(%@)", jsString] completionHandler:nil];
  648. }
  649. // 6 页面加载失败时调用
  650. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
  651. NSLog(@"6-------页面加载失败时调用");
  652. }
  653. // 接收到服务器跳转请求之后调用
  654. - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
  655. NSLog(@"-------接收到服务器跳转请求之后调用");
  656. }
  657. // 数据加载发生错误时调用
  658. - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
  659. NSLog(@"----数据加载发生错误时调用");
  660. }
  661. - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
  662. {
  663. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  664. if (challenge.previousFailureCount == 0) {
  665. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  666. completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
  667. } else {
  668. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  669. }
  670. }
  671. }
  672. //当因为某些问题,导致webView进程终止时触发
  673. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
  674. NSLog(@"%s", __func__);
  675. [webView reload];
  676. }
  677. /**
  678. * web界面中有弹出警告框时调用
  679. *
  680. * @param webView 实现该代理的webview
  681. * @param message 警告框中的内容
  682. * @param completionHandler 警告框消失调用
  683. */
  684. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
  685. NSLog(@"-------web界面中有弹出警告框时调用");
  686. NSLog(@"%@",message);
  687. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  688. message:nil
  689. preferredStyle:UIAlertControllerStyleAlert];
  690. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  691. style:UIAlertActionStyleCancel
  692. handler:^(UIAlertAction *action) {
  693. completionHandler();
  694. }]];
  695. [self presentViewController:alertController animated:YES completion:nil];
  696. }
  697. // 取消和确认的按钮
  698. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
  699. // js 里面的alert实现,如果不实现,网页的alert函数无效 ,
  700. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  701. message:nil
  702. preferredStyle:UIAlertControllerStyleAlert];
  703. [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
  704. style:UIAlertActionStyleDefault
  705. handler:^(UIAlertAction *action) {
  706. completionHandler(YES);
  707. }]];
  708. [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
  709. style:UIAlertActionStyleCancel
  710. handler:^(UIAlertAction *action){
  711. completionHandler(NO);
  712. }]];
  713. [self presentViewController:alertController animated:YES completion:^{}];
  714. }
  715. #pragma mark - KVO回馈
  716. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  717. if ([keyPath isEqualToString:@"estimatedProgress"]) {
  718. self.progressLayer.opacity = 1;
  719. if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
  720. return;
  721. }
  722. self.progressLayer.frame = CGRectMake(0, 0, kScreenWidth*[change[@"new"] floatValue], 3);
  723. if ([change[@"new"]floatValue] == 1.0) {
  724. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  725. self.progressLayer.opacity = 0;
  726. self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
  727. });
  728. }
  729. }else if ([keyPath isEqualToString:@"title"]) {
  730. // 顶部title
  731. self.headTitle = change[@"new"];
  732. if (self.hiddenNavBar == NO) {
  733. self.navView.topTitleLabel.text = self.headTitle;
  734. }
  735. }
  736. }
  737. /*
  738. #pragma mark - Navigation
  739. // In a storyboard-based application, you will often want to do a little preparation before navigation
  740. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  741. // Get the new view controller using [segue destinationViewController].
  742. // Pass the selected object to the new view controller.
  743. }
  744. */
  745. - (void)configLocalStorage {
  746. _hasModify = YES;
  747. if (![NSString isEmptyString:UserDefault(TokenKey)]) {
  748. NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('Authorization', '%@ %@')",UserDefault(Token_type), UserDefault(TokenKey)];
  749. [self.myWebView evaluateJavaScript:jsString completionHandler:nil];
  750. }
  751. }
  752. - (void)setupProgress {
  753. UIView *progress = [[UIView alloc]init];
  754. progress.frame = CGRectMake(0, 0, kScreenWidth, 3);
  755. progress.backgroundColor = [UIColor clearColor];
  756. [self.view addSubview:progress];
  757. CALayer *layer = [CALayer layer];
  758. layer.frame = CGRectMake(0, 0, 0, 3);
  759. layer.backgroundColor = THEMECOLOR.CGColor;
  760. [progress.layer addSublayer:layer];
  761. self.progressLayer = layer;
  762. }
  763. + (WKProcessPool*)singleWkProcessPool {
  764. static WKProcessPool *sharedPool;
  765. static dispatch_once_t onceToken;
  766. dispatch_once(&onceToken, ^{
  767. sharedPool = [[WKProcessPool alloc] init];
  768. });
  769. return sharedPool;
  770. }
  771. - (NSDictionary *)convertJsonStringToNSDictionary:(NSString *)jsonString {
  772. if (jsonString == nil) {
  773. return nil;
  774. }
  775. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  776. NSError *error;
  777. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
  778. if (error) {
  779. NSLog(@"jsonString解析失败:%@", error);
  780. return nil;
  781. }
  782. return json;
  783. }
  784. - (void)setHiddenNavBar:(BOOL)hiddenNavBar {
  785. _hiddenNavBar = hiddenNavBar;
  786. if (hiddenNavBar) {
  787. self.navView.topTitleLabel.text = @"";
  788. }
  789. else {
  790. self.navView.topTitleLabel.text = self.headTitle;
  791. }
  792. }
  793. #pragma mark --- lazying
  794. - (KSWebNavView *)navView {
  795. if (!_navView) {
  796. _navView = [[KSWebNavView alloc] init];
  797. }
  798. return _navView;
  799. }
  800. - (KSWebBackButton *)webBackButton {
  801. if (!_webBackButton) {
  802. _webBackButton = [[KSWebBackButton alloc] init];
  803. MJWeakSelf;
  804. [_webBackButton webViewBackAction:^{
  805. [weakSelf backAction];
  806. }];
  807. }
  808. return _webBackButton;
  809. }
  810. - (void)dealloc {
  811. [[_myWebView configuration].userContentController removeScriptMessageHandlerForName:@"COLEXIU"];
  812. [_myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
  813. [_myWebView removeObserver:self forKeyPath:@"title"];
  814. [_myWebView loadHTMLString:@"" baseURL:nil];
  815. [_myWebView removeFromSuperview];
  816. _myWebView = nil;
  817. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  818. [[NSURLCache sharedURLCache] setDiskCapacity:0];
  819. [[NSURLCache sharedURLCache] setMemoryCapacity:0];
  820. [[NSNotificationCenter defaultCenter] removeObserver:self];
  821. }
  822. - (NSString *)getSaveSpeedPath {
  823. // 在Documents目录下创建一个名为AudioSpeedFile的文件夹
  824. NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioSpeedFile"];
  825. NSLog(@"%@",path);
  826. NSFileManager *fileManager = [NSFileManager defaultManager];
  827. BOOL isDir = FALSE;
  828. BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
  829. if(!(isDirExist && isDir)) {
  830. BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  831. if(!bCreateDir){
  832. NSLog(@"创建文件夹失败!");
  833. }
  834. NSLog(@"创建文件夹成功,文件路径%@",path);
  835. }
  836. path = [path stringByAppendingPathComponent:@"songSpeed.plist"];
  837. NSLog(@"file path:%@",path);
  838. return path;
  839. }
  840. #pragma mark -- 上传图片
  841. - (void)hudTipWillShow:(BOOL)willShow{
  842. if (willShow) {
  843. [self resignFirstResponder];
  844. UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
  845. if (!_HUD) {
  846. _HUD = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
  847. _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
  848. _HUD.label.text = @"正在上传视频...";
  849. _HUD.contentColor = [UIColor whiteColor];
  850. _HUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
  851. _HUD.bezelView.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.8];
  852. _HUD.removeFromSuperViewOnHide = YES;
  853. }else{
  854. _HUD.progress = 0;
  855. [keyWindow addSubview:_HUD];
  856. [_HUD showAnimated:YES];
  857. }
  858. }else{
  859. [_HUD hideAnimated:YES];
  860. }
  861. }
  862. - (void)uploadImageArray:(NSMutableArray *)imageArray {
  863. [self showhud];
  864. NSMutableArray *imageDataArray = [NSMutableArray array];
  865. for (UIImage *image in imageArray) {
  866. NSData *imgData = [UIImage turnsImaegDataByImage:image];
  867. [imageDataArray addObject:imgData];
  868. }
  869. [[KSUploadManager shareInstance] mutilUploadImage:imageDataArray fileName:@"complainImg" successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  870. [self removehub];
  871. NSMutableArray *urlArray = [NSMutableArray array];
  872. for (NSString *url in fileUrlArray) {
  873. [urlArray addObject:url];
  874. }
  875. NSString *attachments = [urlArray componentsJoinedByString:@","];
  876. if (self.chooseFileParm) { // 回调
  877. [self.chooseFileParm setValue:attachments forKey:@"fileUrl"];
  878. [self postMessage:self.chooseFileParm];
  879. self.chooseFileParm = nil;
  880. }
  881. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  882. [self removehub];
  883. [self MBPShow:descMessaeg];
  884. [self fileChooseErrorCallback];
  885. }];
  886. }
  887. #pragma mark --- 上传视频文件
  888. - (void)uploadVideoWithUrl:(NSString *)videoUrl {
  889. // 取出视频第一帧
  890. UIImage *previewImage = [self firstFrameWithVideoURL:[NSURL fileURLWithPath:videoUrl] size:CGSizeMake(1280, 720)];
  891. __block NSString *imageUrl = @"";
  892. if (previewImage) { // 如果有第一帧
  893. NSData *imgData = [UIImage turnsImaegDataByImage:previewImage];
  894. NSString *fileName = @"videoPreviewImg";
  895. [[KSUploadManager shareInstance] uploadImage:imgData fileName:fileName successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  896. NSString *url = [fileUrlArray lastObject];
  897. imageUrl = url;
  898. [self submitUrlWith:imageUrl videoUrl:videoUrl];
  899. } faliure:^(NSError * _Nullable error, NSString *descMessaeg) {
  900. if ([NSString isEmptyString:descMessaeg]) {
  901. [self MBPShow:descMessaeg];
  902. }
  903. [self fileChooseErrorCallback];
  904. }];
  905. }
  906. else {
  907. [self submitUrlWith:nil videoUrl:videoUrl];
  908. }
  909. }
  910. - (void)submitUrlWith:(NSString *)imgUrl videoUrl:(NSString *)videoUrl {
  911. // 上传视频
  912. [self hudTipWillShow:YES];
  913. NSURL *uploadFileUrl = [NSURL fileURLWithPath:videoUrl];
  914. NSData *fileData = [NSData dataWithContentsOfURL:uploadFileUrl];
  915. NSString *suffix = [NSString stringWithFormat:@".%@",[uploadFileUrl pathExtension]];
  916. [[KSUploadManager shareInstance] videoUpload:fileData fileName:@"video" fileSuffix:suffix progress:^(int64_t bytesWritten, int64_t totalBytes) {
  917. dispatch_main_async_safe(^{
  918. // 显示进度
  919. if (self.HUD) {
  920. self.HUD.progress = bytesWritten / totalBytes;// progress是回调进度
  921. }
  922. });
  923. } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  924. [self hudTipWillShow:NO];
  925. NSString *fileUrl = [fileUrlArray lastObject];
  926. [self videoUploadCallback:fileUrl firstFrameImg:imgUrl];
  927. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  928. [self hudTipWillShow:NO];
  929. if ([NSString isEmptyString:descMessaeg]) {
  930. [self MBPShow:descMessaeg];
  931. }
  932. [self videoUploadCallback:@"" firstFrameImg:@""];
  933. }];
  934. }
  935. - (void)videoUploadCallback:(NSString *)remoteVideoUrl firstFrameImg:(NSString *)imgUrl {
  936. if (self.chooseFileParm) { // 回调
  937. [self.chooseFileParm setValue:remoteVideoUrl forKey:@"fileUrl"];
  938. [self.chooseFileParm setValue:imgUrl forKey:@"firstFrameImg"];
  939. [self postMessage:self.chooseFileParm];
  940. self.chooseFileParm = nil;
  941. }
  942. }
  943. #pragma mark ---- 获取图片第一帧
  944. - (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
  945. {
  946. // 获取视频第一帧
  947. NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
  948. AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
  949. AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
  950. generator.appliesPreferredTrackTransform = YES;
  951. generator.maximumSize = CGSizeMake(size.width, size.height);
  952. NSError *error = nil;
  953. CGImageRef imgRef = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
  954. if (imgRef) {
  955. UIImage *image = [UIImage imageWithCGImage:imgRef];
  956. CGImageRelease(imgRef);
  957. return image;
  958. }
  959. else {
  960. return nil;
  961. }
  962. }
  963. #pragma mark ---- UIDocumentPickerDelegate
  964. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
  965. [self fileChooseErrorCallback];
  966. }
  967. - (void)fileChooseErrorCallback {
  968. if (self.chooseFileParm) { // 回调
  969. [self.chooseFileParm setValue:@"" forKey:@"fileUrl"];
  970. [self postMessage:self.chooseFileParm];
  971. self.chooseFileParm = nil;
  972. }
  973. }
  974. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
  975. NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
  976. NSString *fileName = [array lastObject];
  977. fileName = [fileName stringByRemovingPercentEncoding];
  978. if (self.fileChooseType == CHOOSETYPE_XML) {
  979. if (![fileName hasSuffix:@".xml"]) {
  980. [self MBPShow:@"请上传XML格式文件"];
  981. [self fileChooseErrorCallback];
  982. return;
  983. }
  984. }
  985. else if (self.fileChooseType == CHOOSETYPE_MIDI) {
  986. if (![fileName hasSuffix:@".mid"] || [fileName hasSuffix:@".midi"]) {
  987. [self MBPShow:@"请上传mid格式文件"];
  988. [self fileChooseErrorCallback];
  989. return;
  990. }
  991. }
  992. else if (self.fileChooseType == CHOOSETYPE_MP3) {
  993. if (![fileName hasSuffix:@".mp3"]) {
  994. [self MBPShow:@"请上传mp3格式文件"];
  995. [self fileChooseErrorCallback];
  996. return;
  997. }
  998. }
  999. else {
  1000. if (![fileName hasSuffix:@".mp3"] && ![fileName hasSuffix:@".aac"]) {
  1001. [self MBPShow:@"暂不支持此格式!"];
  1002. [self fileChooseErrorCallback];
  1003. return;
  1004. }
  1005. }
  1006. __block NSString * fileUrl = @"";
  1007. if ([KSICloudManager iCloudEnable]) {
  1008. [KSICloudManager downloadWithDocumentURL:url callBack:^(id obj) {
  1009. NSData *data = obj;
  1010. //写入沙盒Documents
  1011. NSString *pathStr = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",fileName]];
  1012. [data writeToFile:pathStr atomically:YES];
  1013. if (![[NSFileManager defaultManager] fileExistsAtPath:pathStr]) {
  1014. BOOL isSuccess = [data writeToFile:pathStr atomically:YES];
  1015. if (isSuccess) {
  1016. fileUrl = pathStr;
  1017. }
  1018. else {
  1019. [self MBPShow:@"写入文件错误!"];
  1020. [self fileChooseErrorCallback];
  1021. }
  1022. }
  1023. else {
  1024. fileUrl = pathStr;
  1025. }
  1026. [self uploadFile:fileName fileUrl:pathStr];
  1027. }];
  1028. }
  1029. else {
  1030. [self MBPShow:@"iCloud不可用!"];
  1031. [self fileChooseErrorCallback];
  1032. }
  1033. }
  1034. - (void)uploadFile:(NSString *)fileName fileUrl:(NSString *)fileUrl {
  1035. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1036. [self showhud];
  1037. NSString *suffix = [NSString stringWithFormat:@".%@",[[fileName componentsSeparatedByString:@"."] lastObject]];
  1038. NSData *fileData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:fileUrl]];
  1039. [[KSUploadManager shareInstance] uploadFile:fileData fileName:@"file" fileSuffix:suffix successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
  1040. [self removehub];
  1041. NSString *fileUrl = [fileUrlArray lastObject];
  1042. if (self.chooseFileParm) { // 回调
  1043. [self.chooseFileParm setValue:fileUrl forKey:@"fileUrl"];
  1044. [self postMessage:self.chooseFileParm];
  1045. self.chooseFileParm = nil;
  1046. }
  1047. } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
  1048. [self removehub];
  1049. [self MBPShow:descMessaeg];
  1050. [self fileChooseErrorCallback];
  1051. }];
  1052. });
  1053. }
  1054. - (CGFloat)getFileSize:(NSURL *)fileUrl {
  1055. NSFileManager *fileManager = [NSFileManager defaultManager];
  1056. float filesize = -1.0;
  1057. NSString *path = fileUrl.path;
  1058. if ([fileManager fileExistsAtPath:path]) {
  1059. NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
  1060. unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
  1061. filesize = 1.0*size/1024/1024;
  1062. }
  1063. return filesize;
  1064. }
  1065. /*
  1066. #pragma mark - Navigation
  1067. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1068. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1069. // Get the new view controller using [segue destinationViewController].
  1070. // Pass the selected object to the new view controller.
  1071. }
  1072. */
  1073. @end