KSBaseWKWebViewController.m 47 KB

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