JYNewSubViewController.m 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. //
  2. // JYNewSearchViewController.m
  3. // JianYuIOS
  4. //
  5. // Created by apple on 2020/6/5.
  6. // Copyright © 2020 lixianglan. All rights reserved.
  7. //
  8. #import "JYNewSubViewController.h"
  9. #import <WebKit/WebKit.h>
  10. #import "JYTabBarController.h"
  11. #import <CoreLocation/CoreLocation.h>
  12. @interface JYNewSubViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,CLLocationManagerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
  13. {
  14. CGPoint startTouch;
  15. BOOL _isMoving;
  16. }
  17. @property (nonatomic, strong) UIProgressView *progressView;
  18. @property (nonatomic, strong) WKWebView *webView;
  19. @property(nonatomic, assign)BOOL updateNotify;
  20. @property(nonatomic, strong)NoNetView *noNetView;
  21. @end
  22. NSString *const new_kInitVector_2 = @"1389461544135476";
  23. size_t const new_kKeySize_2 = kCCKeySizeAES128;
  24. NSString *const new_AesKey_2 = @"mGlAgnIBB8bx2nch";
  25. @implementation JYNewSubViewController
  26. -(void)viewWillAppear:(BOOL)animated
  27. {
  28. [super viewWillAppear:animated];
  29. [self.navigationController setNavigationBarHidden:YES animated:animated];
  30. if([GlobalData shareInstance].isReLogin) {
  31. [GlobalData shareInstance].isReLogin = NO;
  32. [self webViewFirstRequest];
  33. }else {
  34. if([GlobalData shareInstance].subIsRed) {
  35. [GlobalData shareInstance].subIsRed = NO;
  36. [self webViewFirstRequest];
  37. }
  38. }
  39. }
  40. //进度条
  41. - (UIProgressView *)progressView
  42. {
  43. if (_progressView == nil) {
  44. _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,STATUS_BAR_HEIGHT - 2,WIDTH,2)];
  45. _progressView.tintColor = [UIColor blueColor];
  46. _progressView.trackTintColor = [UIColor whiteColor];
  47. }
  48. return _progressView;
  49. }
  50. //懒加载
  51. - (WKWebView *)webView
  52. {
  53. if(_webView == nil) {
  54. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  55. config.preferences = [[WKPreferences alloc] init];
  56. config.preferences.minimumFontSize = 0;
  57. config.preferences.javaScriptEnabled = YES;
  58. config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
  59. //添加消息处理,注意:self指代的是需要遵守WKScriptMessageHandler协议,结束时需要移除
  60. config.userContentController = [[WKUserContentController alloc] init];
  61. //声明协议
  62. NSArray *jsArr = @[@"loginByWeixin",
  63. @"share",
  64. @"saveUserToken",
  65. @"removeUserToken",
  66. @"openSystemNotification",
  67. @"openExternalLink",
  68. @"alert",
  69. @"hiddenBottom",
  70. @"checkLab",
  71. @"loginSuccess",
  72. @"backUrl",
  73. @"clearPushMessage",
  74. @"hideRedSpotOnMenu",
  75. @"showRedSpotOnMenu",
  76. @"wxPay",
  77. @"aliPay",
  78. @"skipCamera",
  79. @"skipAlbum",
  80. @"appTest",
  81. ];
  82. for (NSString*jsName in jsArr) {
  83. [config.userContentController addScriptMessageHandler:self name:jsName];
  84. }
  85. //高端的自定义配置创建WKWebView
  86. if (iPhoneX) {
  87. _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-TAB_BAR_HEIGHT) configuration:config];
  88. if (@available(iOS 11.0, *)) {
  89. _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  90. }
  91. }else {
  92. _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT-TAB_BAR_HEIGHT+STATUS_BAR_HEIGHT) configuration:config];
  93. }
  94. _webView.scrollView.bounces = NO;
  95. _webView.UIDelegate = self;
  96. _webView.navigationDelegate = self;
  97. // _webView.allowsBackForwardNavigationGestures = true;
  98. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  99. }
  100. return _webView;
  101. }
  102. -(void)webViewFirstRequest
  103. {
  104. NSString *url = [NSString stringWithFormat:@"%@%@", kHost, @"jyapp/swordfish/historypush"];
  105. url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  106. NSLog(@"222 :第一次加载:%@",url);
  107. kMainQueue(^{
  108. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  109. })
  110. }
  111. #pragma mark - event response
  112. // 计算wkWebView进度条
  113. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  114. if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
  115. CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
  116. self.progressView.alpha = 1.0f;
  117. [self.progressView setProgress:newprogress animated:YES];
  118. if (newprogress >= 1.0f) {
  119. [UIView animateWithDuration:0.3f
  120. delay:0.3f
  121. options:UIViewAnimationOptionCurveEaseOut
  122. animations:^{
  123. self.progressView.alpha = 0.0f;
  124. }
  125. completion:^(BOOL finished) {
  126. [self.progressView setProgress:0 animated:NO];
  127. }];
  128. }
  129. } else {
  130. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  131. }
  132. }
  133. -(void)initNotification {
  134. //加载通知
  135. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestWebView:) name:kRequestWebViewWithUrl object:nil];
  136. //点击订阅通知
  137. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickSubNotiMethods:) name:ClickSubNotiMethods object:nil];
  138. //点击支付通知
  139. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickPayMethods:) name:ClickPayMethods object:nil];
  140. //支付状态通知
  141. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayWXpayStatus:) name:AlipayWXpayStatus object:nil];
  142. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotifyState) name:kUpdateNotifyState object:nil];
  143. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(afterReceiveNewMsg) name:kAfterReceiveNewMsg object:nil];
  144. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadWebView) name:kReloadWebVIew object:nil];
  145. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOut:) name:kLoginOut object:nil];
  146. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netReachChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
  147. //展示底部红的通知
  148. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsRedPoint:) name:JYNewsRedPoint object:nil];
  149. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDY:) name:@"refreshDY" object:nil];
  150. //接收全新通知
  151. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshNonCurVC:) name:RefreshNonCurVC object:nil];
  152. }
  153. #pragma mark – Gesture Recognizer –
  154. -(void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
  155. {
  156. NSString *current_url = [self stringByEvaluatingJavaScriptFromString:@"document.location.href"];
  157. NSLog(@"当前页面:%@",current_url);
  158. CGRect rect = self.view.bounds;
  159. CGFloat width = CGRectGetWidth(rect);
  160. if (![self.webView canGoBack]) {
  161. NSLog(@"不可返回");
  162. return;
  163. }
  164. if([current_url containsString:@"jyapp/free/login"]) {
  165. return;
  166. }
  167. // NSString *current_url = self.webView.request.URL.absoluteString;
  168. if([current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/free/me",kHost]]||[current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/jylab/index",kHost]]||[current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/swordfish/historypush",kHost]]||[current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/jylab/mainSearch",kHost]]){
  169. return;
  170. }
  171. CGPoint touchPoint = [recoginzer locationInView:[UIApplication sharedApplication].keyWindow];
  172. if (recoginzer.state==UIGestureRecognizerStateBegan) {
  173. _isMoving = YES;
  174. startTouch = touchPoint;
  175. } else if (recoginzer.state==UIGestureRecognizerStateEnded){
  176. if (touchPoint.x - startTouch.x > width*0.125) {
  177. [UIView animateWithDuration:0.3 animations:^{
  178. [self moveViewWithX:width];
  179. // [GlobalData shareInstance].isSideslip = YES;
  180. [self.webView goBack];
  181. // [self isExitCallToJS:@"afterClickBack()" withMethodName:@"afterClickBack"];
  182. } completion:^(BOOL finished) {
  183. _isMoving = NO;
  184. [self moveViewWithX:0];
  185. }];
  186. } else {
  187. [UIView animateWithDuration:0.3 animations:^{
  188. [self moveViewWithX:0];
  189. } completion:^(BOOL finished) {
  190. _isMoving = NO;
  191. }];
  192. }
  193. return;
  194. } else if (recoginzer.state==UIGestureRecognizerStateCancelled){
  195. [UIView animateWithDuration:0.3 animations:^{
  196. [self moveViewWithX:0];
  197. } completion:^(BOOL finished) {
  198. _isMoving = NO;
  199. }];
  200. return;
  201. }
  202. if (_isMoving) {
  203. [self moveViewWithX:touchPoint.x - startTouch.x];
  204. }
  205. }
  206. -(void)moveViewWithX:(float)x
  207. {
  208. CGRect rect = self.view.bounds;
  209. CGFloat width = CGRectGetWidth(rect);
  210. x = x>width?width:x;
  211. x = x<0?0:x;
  212. CGRect frame = self.webView.frame;
  213. frame.origin.x = x;
  214. self.webView.frame = frame;
  215. }
  216. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
  217. // message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
  218. // NSLog(@"原生收到了js发送过来的消息message.name = %@ message.body = %@",message.name,message.body);
  219. if ([message.name isEqualToString:@"loginByWeixin"]) {
  220. [self jsLoginByWeixin:message.body];
  221. }else if ([message.name isEqualToString:@"share"]) {
  222. [self jsShare:message.body];
  223. }else if ([message.name isEqualToString:@"saveUserToken"]) {
  224. [self jsSaveUserToken:message.body];
  225. }else if ([message.name isEqualToString:@"removeUserToken"]) {
  226. [self jsRemoveUserToken:message.body];
  227. }else if ([message.name isEqualToString:@"openSystemNotification"]) {
  228. [self jsOpenSystemNotification:message.body];
  229. }else if ([message.name isEqualToString:@"openExternalLink"]) {
  230. [self JsOpenExternalLink:message.body];
  231. }else if ([message.name isEqualToString:@"alert"]) {
  232. [self jsAlert:message.body];
  233. }else if ([message.name isEqualToString:@"hiddenBottom"]) {
  234. [self jsHiddenBottom:message.body];
  235. }else if ([message.name isEqualToString:@"checkLab"]) {
  236. [self jsCheckLab:message.body];
  237. }else if ([message.name isEqualToString:@"loginSuccess"]) {
  238. [self jsLoginSuccess:message.body];
  239. }else if ([message.name isEqualToString:@"backUrl"]) {
  240. [self jsBackUrl:message.body];
  241. }else if ([message.name isEqualToString:@"clearPushMessage"]) {
  242. [self jsClearPushMessage:message.body];
  243. }else if ([message.name isEqualToString:@"hideRedSpotOnMenu"]) {
  244. [self jsHideRedSpotOnMenu:message.body];
  245. }else if ([message.name isEqualToString:@"showRedSpotOnMenu"]) {
  246. [self jsShowRedSpotOnMenu:message.body];
  247. }else if ([message.name isEqualToString:@"wxPay"]) {
  248. [self jsWxPay:message.body];
  249. }else if ([message.name isEqualToString:@"aliPay"]) {
  250. [self jsAliPay:message.body];
  251. }else if ([message.name isEqualToString:@"skipCamera"]) {
  252. [self jsSkipCamera:message.body];
  253. }else if ([message.name isEqualToString:@"skipAlbum"]) {
  254. [self jsSkipAlbum:message.body];
  255. }else {
  256. }
  257. }
  258. #pragma mark - WKUIDelegate
  259. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
  260. {
  261. NSError *err = nil;
  262. NSData *dataFromString = [prompt dataUsingEncoding:NSUTF8StringEncoding];
  263. NSDictionary *paramdict = [NSJSONSerialization JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:&err];
  264. if (!err){
  265. NSString *type = [paramdict objectForKey:@"jsName"];
  266. if (type && [type isEqualToString:@"getUserToken"]) {
  267. NSDictionary *dict = @{@"type":@"string",
  268. @"value":[self jsGetUserToken:paramdict]};
  269. completionHandler([self convertToJsonData:dict]);
  270. }else if (type && [type isEqualToString:@"getVersion"]) {
  271. NSDictionary *dict = @{@"type":@"string",
  272. @"value":[self jsGetVersion:paramdict]};
  273. completionHandler([self convertToJsonData:dict]);
  274. }else if (type && [type isEqualToString:@"checkNoticePermission"]) {
  275. NSDictionary *dict = @{@"type":@"int",
  276. @"value":[NSString stringWithFormat:@"%d",[self jsCheckNoticePermission:paramdict]]};
  277. completionHandler([self convertToJsonData:dict]);
  278. }else if (type && [type isEqualToString:@"getPushRid"]) {
  279. NSDictionary *dict = @{@"type":@"string",@"value":[self jsGetPushRid:paramdict]};
  280. completionHandler([self convertToJsonData:dict]);
  281. }else if (type && [type isEqualToString:@"isInstallWeixin"]) {
  282. NSDictionary *dict = @{@"type":@"int",
  283. @"value":[NSString stringWithFormat:@"%d",[self jsIsInstallWeixin:paramdict]]};
  284. completionHandler([self convertToJsonData:dict]);
  285. }else if (type && [type isEqualToString:@"getCipherText"]) {
  286. NSDictionary *dict = @{@"type":@"string",
  287. @"value":[self jsGetCipherText:paramdict]};
  288. completionHandler([self convertToJsonData:dict]);
  289. }
  290. else if (type && [type isEqualToString:@"getOtherPushRid"]) {
  291. NSDictionary *dict = @{@"type":@"string",@"value":[self jsGetOtherPushRid:paramdict]};
  292. completionHandler([self convertToJsonData:dict]);
  293. }else if (type && [type isEqualToString:@"getPhoneBrand"]) {
  294. NSDictionary *dict = @{@"type":@"string",
  295. @"value":[self jsGetPhoneBrand:paramdict]};
  296. completionHandler([self convertToJsonData:dict]);
  297. }else {
  298. completionHandler(@"");
  299. }
  300. }
  301. }
  302. //通过js alert 显示一个警告面板,调用原生会走此方法。
  303. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  304. {
  305. NSLog(@"显示一个JavaScript警告面板, message = %@",message);
  306. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
  307. [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  308. completionHandler();
  309. }]];
  310. [self presentViewController:alertController animated:YES completion:nil];
  311. }
  312. //通过 js confirm 显示一个确认面板,调用原生会走此方法。
  313. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
  314. {
  315. NSLog(@"运行JavaScript确认面板, message = %@", message);
  316. UIAlertController *action = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
  317. [action addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  318. completionHandler(NO);
  319. }] ];
  320. [action addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  321. completionHandler(YES);
  322. }]];
  323. [self presentViewController:action animated:YES completion:nil];
  324. }
  325. #pragma mark - OC调JS交互
  326. -(void)isExitCallToJS:(NSString *)jsStr withMethodName:(NSString *)name{
  327. NSString *jsName = [NSString stringWithFormat:@"function exist(){return !window['%@']};exist()",name];
  328. [_webView evaluateJavaScript:jsName completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  329. NSLog(@"是否存在 result:%@,error:%@",result,error);
  330. if ([result intValue]==0) {
  331. [self executeCallJS:jsStr];
  332. }else {
  333. NSLog(@"不存在-不存在-不存在-%@",jsStr);
  334. }
  335. }];
  336. }
  337. -(void)executeCallJS:(NSString *)jsStr {
  338. NSLog(@"OC调JS交互%@:",jsStr);
  339. [_webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  340. if (error!=nil) {
  341. NSLog(@"result:%@,error:%@",result,error);
  342. [[LXViewControllerManager shareViewControllerManager]showAlertViewWithMessage: jsStr];
  343. [[GlobalData shareInstance] addOnePlistData:@{
  344. @"detail":[[self stringByEvaluatingJavaScriptFromString:@"document.location.href"] stringByAppendingString:[NSString stringWithFormat:@"\nJS异常方法:%@\n%@",jsStr,[error description]]],
  345. @"reqTime":[NSNumber numberWithInt:0],
  346. }];
  347. }
  348. }];
  349. }
  350. - (void)viewDidLoad {
  351. [super viewDidLoad];
  352. // Do any additional setup after loading the view.
  353. NSLog(@"订阅初始化");
  354. self.view.backgroundColor = [UIColor whiteColor];
  355. [self.view addSubview:self.webView];
  356. [self.view addSubview:self.progressView];
  357. [self webViewFirstRequest];
  358. [[AFNetworkReachabilityManager sharedManager] startMonitoring];
  359. [self initNotification];
  360. UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(paningGestureReceive:)];
  361. [recognizer delaysTouchesBegan];
  362. [self.view addGestureRecognizer:recognizer];
  363. //监听底部栏
  364. [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(bottomTwoListening) userInfo:nil repeats:YES];
  365. }
  366. -(void)bottomTwoListening {
  367. NSLog(@"tab-sub");
  368. if(self.tabBarController.selectedIndex == 1) {
  369. [self judgeIsHiddenBottom];
  370. }
  371. }
  372. #pragma mark - WKNavigationDelegate
  373. /* 页面加载完成 */
  374. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
  375. NSString *curUrl = [self stringByEvaluatingJavaScriptFromString:@"document.location.href"];
  376. NSLog(@"-----页面加载完成%@",curUrl);
  377. //正常的网页加载
  378. [self judgeIsHiddenBottom];//是否隐藏
  379. [self removeNoNetViews];
  380. [[LXViewControllerManager shareViewControllerManager] hideHud];
  381. }
  382. //-(void)afterPageClick {
  383. // [self isExitCallToJS:@"afterPageInit()" withMethodName:@"afterPageInit"];
  384. //}
  385. // 页面开始加载时调用
  386. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
  387. }
  388. // 当内容开始返回时调用
  389. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
  390. }
  391. // 页面加载失败时调用
  392. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(nonnull NSError *)error{
  393. [[GlobalData shareInstance] addOnePlistData:@{
  394. @"detail":[[self stringByEvaluatingJavaScriptFromString:@"document.location.href"] stringByAppendingString:[NSString stringWithFormat:@"\n%@",[error description]]],
  395. @"reqTime":[NSNumber numberWithInt:0],
  396. }];
  397. }
  398. #pragma mark *****JS与OC交互
  399. #pragma mark - WKScriptMessageHandler JS调OC交互
  400. -(void)jsLoginByWeixin:(NSDictionary *)dict {
  401. if ([LXUserDefaults isInstallWeiXin] != 1) { // 没有安装微信 不走友盟
  402. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"微信登录失败,没有安装微信" delay:1.5];
  403. return;
  404. }
  405. [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error) {
  406. UMSocialUserInfoResponse *resp = result;
  407. [self dealWXDic:(NSDictionary *)resp.originalResponse];
  408. [[LXViewControllerManager shareViewControllerManager] hideHud];
  409. }];
  410. }
  411. // 处理微信登录获取到的数据
  412. -(void)dealWXDic:(NSDictionary *)dictionary{
  413. [[LXViewControllerManager shareViewControllerManager] showHudText:nil];
  414. //如果获取到用户信息,即用户点击了“登录”,则进行用户信息获取
  415. if (dictionary.count > 0) {
  416. NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:dictionary];
  417. if (dic) {
  418. [dic removeObjectForKey:@"privilege"];
  419. [dic removeObjectForKey:@"language"];
  420. double currDouble = [[NSDate date] timeIntervalSince1970];
  421. [dic setObject:[NSNumber numberWithLong:(long)currDouble] forKey:@"createtime"];
  422. // 拼接标志位
  423. NSString *sign = [NSString stringWithFormat:@"city=%@&country=%@&createtime=%@&headimgurl=%@&nickname=%@&openid=%@&province=%@&sex=%@&unionid=%@", dic[@"city"], dic[@"country"], dic[@"createtime"], dic[@"headimgurl"], dic[@"nickname"], dic[@"openid"], dic[@"province"],dic[@"sex"],dic[@"unionid"]];
  424. sign = [LXMD5 md532BitLower:sign];
  425. [dic setObject:sign forKey:@"sign"];
  426. NSString *endStr = [[LXViewControllerManager shareViewControllerManager] getJsonStr:dic];
  427. NSData *data = [endStr dataUsingEncoding:NSUTF8StringEncoding];
  428. endStr = [data base64EncodedStringWithOptions:0];
  429. [self isExitCallToJS:[NSString stringWithFormat:@"loginByWeixinCallBack('%@')", endStr] withMethodName:@"loginByWeixinCallBack"];
  430. }
  431. }
  432. }
  433. -(void)jsShare:(NSDictionary *)dict {
  434. NSString *type = [NSString stringWithFormat:@"%@",dict[@"type"]];
  435. NSString *title = [NSString stringWithFormat:@"%@",dict[@"title"]];
  436. NSString *content = [NSString stringWithFormat:@"%@",dict[@"content"]];
  437. NSString *link = [NSString stringWithFormat:@"%@",dict[@"link"]];
  438. UMSocialPlatformType shareType;
  439. if ([type intValue] == 1) { // 微信好友
  440. shareType = UMSocialPlatformType_WechatSession;
  441. }else if ([type intValue] == 2){ /// qq好友
  442. shareType = UMSocialPlatformType_QQ;
  443. }else if ([type intValue] == 3){ // 朋友圈
  444. shareType = UMSocialPlatformType_WechatTimeLine;
  445. }else{
  446. shareType = UMSocialPlatformType_WechatSession;
  447. }
  448. if ([type intValue] == 1 || [type intValue] == 3) {
  449. if ([LXUserDefaults isInstallWeiXin] != 1) {
  450. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"没有安装微信" delay:1.5];
  451. return;
  452. }
  453. }
  454. if ([type intValue] == 2) {
  455. if (![[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_QQ]) {
  456. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"没有安装QQ" delay:1.5];
  457. return;
  458. }
  459. }
  460. //创建分享消息对象
  461. UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
  462. //创建网页内容对象
  463. UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:content thumImage:[UIImage imageNamed:@"logo"]];
  464. //设置网页地址
  465. shareObject.webpageUrl = link;
  466. messageObject.shareObject = shareObject;
  467. //调用分享接口
  468. [[UMSocialManager defaultManager] shareToPlatform:shareType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
  469. if (error) {
  470. if (error.userInfo[@"message"] && [error.userInfo[@"message"] containsString:@"Operation is cancel"]) {
  471. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"取消分享" delay:1];
  472. }else{
  473. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:error.userInfo[@"message"] delay:1];
  474. }
  475. [self isExitCallToJS:[NSString stringWithFormat:@"shareCallBack('%@','%@')",type,@"0"] withMethodName:@"shareCallBack"];
  476. }else{
  477. if ([data isKindOfClass:[UMSocialShareResponse class]]) {
  478. [self isExitCallToJS:[NSString stringWithFormat:@"shareCallBack('%@','%@')",type,@"1"] withMethodName:@"shareCallBack"];
  479. }else{
  480. UMSocialLogInfo(@"response data is %@",data);
  481. }
  482. }
  483. }];
  484. }
  485. -(void)jsSaveUserToken:(NSDictionary *)dict{
  486. [[LXViewControllerManager shareViewControllerManager] hideHud];
  487. [LXUserDefaults saveToken:[NSString stringWithFormat:@"%@",dict[@"token"]]];
  488. }
  489. -(NSString *)jsGetUserToken:(NSDictionary *)dict{
  490. return [LXUserDefaults token];
  491. }
  492. -(void)jsRemoveUserToken:(NSDictionary *)dict{
  493. [LXUserDefaults clearAll];
  494. }
  495. -(int)jsCheckNoticePermission:(NSDictionary *)dict{
  496. return [LXUserDefaults notifyState];
  497. }
  498. // 跳转到系统设置
  499. -(void)jsOpenSystemNotification:(NSDictionary *)dict{
  500. self.updateNotify = YES;
  501. kMainQueue(^{
  502. [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  503. });
  504. }
  505. // 获取推送id
  506. -(NSString *)jsGetPushRid:(NSDictionary *)dict{
  507. return [LXUserDefaults registrationID];
  508. }
  509. // 打开新页面 加载新web
  510. -(void)JsOpenExternalLink:(NSDictionary *)dict{
  511. NSString *url = [NSString stringWithFormat:@"%@",dict[@"url"]];
  512. NSString *title = [NSString stringWithFormat:@"%@",dict[@"title"]];
  513. if (url) {
  514. if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable || [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusUnknown) {
  515. }
  516. JYNewWebController *ctr = [[JYNewWebController alloc] init];
  517. ctr.url = url;
  518. if (!title || [title isEqualToString:@""] || [title isEqualToString:@"undefined"]) {
  519. ctr.titleShow = nil;
  520. }else{
  521. ctr.titleShow = title;
  522. }
  523. kMainQueue(^{
  524. [self presentViewController:ctr animated:NO completion:nil];
  525. });
  526. }
  527. }
  528. // 获取当前版本号
  529. -(NSString *)jsGetVersion:(NSDictionary *)dict{
  530. return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
  531. }
  532. -(void)jsAlert:(NSDictionary *)dict{
  533. [[LXViewControllerManager shareViewControllerManager] showAlertViewWithMessage:[NSString stringWithFormat:@"%@",dict[@"content"]]];
  534. }
  535. -(int)jsIsInstallWeixin:(NSDictionary *)dict{
  536. return [LXUserDefaults isInstallWeiXin];
  537. }
  538. -(NSString *)jsGetCipherText:(NSDictionary *)dict{
  539. NSDictionary *objDict = [NSDictionary dictionaryWithDictionary:dict[@"arguments"]];
  540. NSString *phone = [NSString stringWithFormat:@"%@",objDict[@"phone"]];
  541. NSDate *date=[NSDate date];
  542. NSDateFormatter *format1=[[NSDateFormatter alloc] init];
  543. [format1 setDateFormat:@"yyyyMMddhhmmss"];
  544. NSString *dateStr;
  545. dateStr=[format1 stringFromDate:date];
  546. NSLog(@"%@",dateStr);
  547. NSString *content = [[NSString stringWithFormat:@"%@_%@",phone,dateStr] stringByAppendingString:[NSString stringWithFormat:@"_%@",[LXMD5 md532BitLower:[NSString stringWithFormat:@"%@&%@",phone,dateStr]]]];
  548. NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
  549. NSUInteger dataLength = contentData.length;
  550. // 为结束符'\\0' +1
  551. char keyPtr[new_kKeySize_2 + 1];
  552. memset(keyPtr, 0, sizeof(keyPtr));
  553. [new_AesKey_2 getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
  554. // 密文长度 <= 明文长度 + BlockSize
  555. size_t encryptSize = dataLength + kCCBlockSizeAES128;
  556. void *encryptedBytes = malloc(encryptSize);
  557. size_t actualOutSize = 0;
  558. NSData *initVector = [new_kInitVector_2 dataUsingEncoding:NSUTF8StringEncoding];
  559. CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
  560. kCCAlgorithmAES,
  561. kCCOptionPKCS7Padding, // 系统默认使用 CBC,然后指明使用 PKCS7Padding
  562. keyPtr,
  563. new_kKeySize_2,
  564. initVector.bytes,
  565. contentData.bytes,
  566. dataLength,
  567. encryptedBytes,
  568. encryptSize,
  569. &actualOutSize);
  570. if (cryptStatus == kCCSuccess) {
  571. // 对加密后的数据进行 base64 编码
  572. return [[NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
  573. }
  574. free(encryptedBytes);
  575. return nil;
  576. }
  577. -(void)jsHiddenBottom:(NSDictionary *)dict{
  578. if(self.tabBarController.selectedIndex == 1) {
  579. if([[NSString stringWithFormat:@"%@",dict[@"hidden"]] integerValue]==0) {
  580. [self hideTabBar];
  581. [self hiddenMethodTabBar];
  582. }else {
  583. [self showTabBar];
  584. [self showMethodTabBar];
  585. }
  586. }
  587. }
  588. -(void)jsCheckLab:(NSDictionary *)dict {
  589. [[NSNotificationCenter defaultCenter] postNotificationName:RefreshNonCurVC object:nil userInfo:nil];
  590. }
  591. //js方法登录成功
  592. -(void)jsLoginSuccess:(NSDictionary *)dict {
  593. NSLog(@"sub登录成功提示");
  594. NSString *status = [NSString stringWithFormat:@"%@",dict[@"status"]];
  595. [GlobalData shareInstance].isReLogin = YES;
  596. if([status isEqualToString:@"S"]) {
  597. kMainQueue(^{
  598. [[NSNotificationCenter defaultCenter] postNotificationName:RefreshAllVC object:nil userInfo:nil];
  599. AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  600. JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
  601. tab.selectedIndex = 0;
  602. });
  603. }else {
  604. }
  605. }
  606. -(void)jsBackUrl:(NSDictionary *)dict {
  607. NSString *status = [NSString stringWithFormat:@"%@",dict[@"status"]];
  608. NSLog(@"sub返回");
  609. if([status isEqualToString:@"H"]) {
  610. //测试返回首页
  611. kMainQueue(^{
  612. [[NSNotificationCenter defaultCenter] postNotificationName:RefreshAllVC object:nil userInfo:nil];
  613. AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  614. JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
  615. tab.selectedIndex = 0;
  616. });
  617. }
  618. }
  619. -(void)jsClearPushMessage:(NSDictionary *)dict {
  620. kMainQueue(^{
  621. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
  622. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
  623. });
  624. }
  625. -(void)jsHideRedSpotOnMenu:(NSDictionary *)dict {
  626. NSString *menu = [NSString stringWithFormat:@"%@",dict[@"menu"]];
  627. if([menu isEqualToString:@"subscribe"]) {
  628. kMainQueue(^{
  629. [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
  630. });
  631. }
  632. if([menu isEqualToString:@"my"]) {
  633. kMainQueue(^{
  634. [self.tabBarController.tabBar hideBadgeOnItemIndex:3];
  635. });
  636. }
  637. }
  638. -(void)jsShowRedSpotOnMenu:(NSDictionary *)dict {
  639. NSString *menu = [NSString stringWithFormat:@"%@",dict[@"menu"]];
  640. if([menu isEqualToString:@"subscribe"]) {
  641. kMainQueue(^{
  642. [self.tabBarController.tabBar showBadgeOnItemIndex:1];
  643. });
  644. }
  645. if([menu isEqualToString:@"my"]) {
  646. kMainQueue(^{
  647. [self.tabBarController.tabBar showBadgeOnItemIndex:3];
  648. });
  649. }
  650. }
  651. -(void)jsWxPay:(NSDictionary *)dict {
  652. NSString *jsonString = [NSString stringWithFormat:@"%@",dict[@"order"]];
  653. if ([LXUserDefaults isInstallWeiXin] != 1) { // 没有安装wx
  654. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"请先安装微信再进行支付!" delay:1.5];
  655. return;
  656. }
  657. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  658. NSError *err;
  659. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
  660. if(err) {
  661. NSLog(@"json解析失败:%@",err);
  662. return;
  663. }
  664. //吊起微信
  665. PayReq *request = [[PayReq alloc] init] ;
  666. request.openID = dic[@"Appid"];
  667. request.partnerId = dic[@"Partnerid"];
  668. request.prepayId= dic[@"Prepayid"];
  669. request.package = @"Sign=WXPay";
  670. request.nonceStr= dic[@"Noncestr"];
  671. request.timeStamp= [dic[@"Timestamp"] intValue];
  672. request.sign= dic[@"Sign"];
  673. kMainQueue(^{
  674. [WXApi sendReq:request];
  675. });
  676. }
  677. -(void)jsAliPay:(NSDictionary *)dict {
  678. NSString *order = [NSString stringWithFormat:@"%@",dict[@"order"]];
  679. kMainQueue(^{
  680. [[AlipaySDK defaultService] payOrder:order fromScheme:@"jianyuiosapp" callback:nil];
  681. });
  682. }
  683. -(NSString *)jsGetOtherPushRid:(NSDictionary *)dict {
  684. return [LXUserDefaults deviceToken];
  685. }
  686. -(NSString *)jsGetPhoneBrand:(NSDictionary *)dict {
  687. UIDevice *device = [UIDevice currentDevice];
  688. return device.platformString;
  689. }
  690. //拍照上传图片
  691. -(void)jsSkipCamera:(NSDictionary *)dict {
  692. UIImagePickerController *picker = [[UIImagePickerController alloc] init];
  693. picker.delegate = self;
  694. picker.allowsEditing = YES;
  695. picker.sourceType = UIImagePickerControllerSourceTypeCamera;
  696. dispatch_async(dispatch_get_main_queue(), ^{
  697. [self presentViewController:picker animated:YES completion:nil];
  698. });
  699. }
  700. //相册选择照片
  701. -(void)jsSkipAlbum:(NSDictionary *)dict {
  702. UIImagePickerController *picker = [[UIImagePickerController alloc] init];
  703. picker.delegate = self;
  704. picker.allowsEditing = YES;
  705. picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  706. dispatch_async(dispatch_get_main_queue(), ^{
  707. [self presentViewController:picker animated:YES completion:nil];
  708. });
  709. }
  710. // web是否可退回上页面
  711. -(int)jsIsCanBack:(NSString *)str{
  712. return self.webView.canGoBack ? 1:0;
  713. }
  714. #pragma mark *****其他方法
  715. -(void)judgeIsHiddenBottom {
  716. if(self.tabBarController.selectedIndex == 1) {
  717. NSString *current_url = [self stringByEvaluatingJavaScriptFromString:@"document.location.href"];
  718. if([current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/swordfish/historypush",kHost]]||[current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/free/login?back=index",kHost]]){
  719. [self showTabBar];
  720. [self showMethodTabBar];
  721. }else {
  722. [self hideTabBar];
  723. [self hiddenMethodTabBar];
  724. }
  725. }
  726. }
  727. -(void)requestWebTime:(NSDictionary *)infoDict
  728. {
  729. NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"url"]];
  730. if([infoDict[@"type"] isEqualToString:@"message"]) {
  731. NSString *url = [NSString stringWithFormat:@"%@",urlStr];
  732. NSArray * array = [url componentsSeparatedByString:@"=="];
  733. url = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  734. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  735. }else if ([infoDict[@"type"] isEqualToString:@"titleMessage"]) {
  736. NSArray * array = [urlStr componentsSeparatedByString:@"=="];
  737. urlStr = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  738. NSString * titleStr = @"消息通知";
  739. titleStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"title"]];
  740. if (urlStr&&self.tabBarController.selectedIndex == 1) {
  741. [self JsOpenExternalLink:@{@"url":urlStr,@"title":titleStr}];
  742. }
  743. }else {
  744. NSString *url = [NSString stringWithFormat:@"%@%@", kHost, urlStr];
  745. url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  746. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  747. }
  748. }
  749. - (void)hideTabBar {
  750. kMainQueue(^{
  751. if (self.tabBarController.tabBar.hidden == YES) {
  752. return;
  753. }
  754. UIView *contentView;
  755. if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
  756. contentView = [self.tabBarController.view.subviews objectAtIndex:1];
  757. else
  758. contentView = [self.tabBarController.view.subviews objectAtIndex:0];
  759. contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y, contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
  760. self.tabBarController.tabBar.hidden = YES;
  761. });
  762. }
  763. - (void)showTabBar{
  764. kMainQueue(^{
  765. if (self.tabBarController.tabBar.hidden == NO)
  766. {
  767. return;
  768. }
  769. UIView *contentView;
  770. if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
  771. contentView = [self.tabBarController.view.subviews objectAtIndex:1];
  772. else
  773. contentView = [self.tabBarController.view.subviews objectAtIndex:0];
  774. contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y, contentView.bounds.size.width, contentView.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
  775. self.tabBarController.tabBar.hidden = NO;
  776. });
  777. }
  778. - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
  779. {
  780. __block NSString *resultString = nil;
  781. __block BOOL finished = NO;
  782. [self.webView evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
  783. if (error == nil) {
  784. if (result != nil) {
  785. resultString = [NSString stringWithFormat:@"%@", result];
  786. }
  787. } else {
  788. NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
  789. }
  790. finished = YES;
  791. }];
  792. while (!finished) {
  793. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
  794. }
  795. return resultString;
  796. }
  797. -(void)hiddenMethodTabBar
  798. {
  799. kMainQueue(^{
  800. if (iPhoneX) {
  801. if (@available(iOS 11.0, *)) {
  802. self.webView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
  803. NSLog(@"%@",self.webView)
  804. }
  805. }else {
  806. self.webView.frame = CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT+STATUS_BAR_HEIGHT);
  807. }
  808. });
  809. }
  810. -(void)showMethodTabBar
  811. {
  812. kMainQueue(^{
  813. if (iPhoneX) {
  814. if (@available(iOS 11.0, *)) {
  815. self.webView.frame = CGRectMake(0, 0, WIDTH, HEIGHT-TAB_BAR_HEIGHT);
  816. }
  817. }else {
  818. self.webView.frame = CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT-TAB_BAR_HEIGHT+STATUS_BAR_HEIGHT);
  819. }
  820. });
  821. }
  822. //取消获取照片
  823. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
  824. {
  825. dispatch_async(dispatch_get_main_queue(), ^{
  826. [picker dismissViewControllerAnimated:YES completion:^{
  827. [self uploadUrl:@""];
  828. }];
  829. });
  830. }
  831. //上传图片
  832. -(void)uploadPic:(NSData *)data
  833. {
  834. NSDictionary * body = @{@"type":@"courseFile"};
  835. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  836. //ContentType设置
  837. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",@"text/plain",nil];
  838. manager.responseSerializer= [AFHTTPResponseSerializer serializer];
  839. manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  840. manager.requestSerializer.timeoutInterval = 15.0f;
  841. [manager POST:[NSString stringWithFormat:@"%@filemanage/upload",kHost] parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  842. //上传的参数(上传图片,以文件流的格式)
  843. [formData appendPartWithFileData:data
  844. name:@"courseFile"
  845. fileName:@"courseFile.jpeg"
  846. mimeType:@"image/jpeg"];
  847. } progress:^(NSProgress * _Nonnull uploadProgress) {
  848. CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
  849. NSLog(@"%.2lf%%", progress);
  850. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  851. //请求成功的block回调
  852. NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
  853. NSLog(@"上传成功%@",dic);
  854. if ([dic[@"msg"] isEqualToString:@"ssss"]) {
  855. [self uploadUrl:dic[@"url"]];
  856. }else{
  857. [self uploadUrl:@""];
  858. }
  859. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  860. NSLog(@"上传失败%@",error);
  861. [self uploadUrl:@""];
  862. [[GlobalData shareInstance] addOnePlistData:@{
  863. @"detail":@"上传图片接口",
  864. @"reqTime":[NSNumber numberWithInt:0],
  865. }];
  866. }];
  867. }
  868. -(void)uploadUrl:(NSString *)url {
  869. NSString *textJS = [NSString new];
  870. NSString *methodJS = [NSString new];
  871. if ([url isEqualToString:@""]) {
  872. textJS = @"hiddenLoading()";
  873. methodJS =@"hiddenLoading";
  874. }else{
  875. textJS = [NSString stringWithFormat:@"uploadImg('%@')",url];
  876. methodJS = @"uploadImg";
  877. }
  878. if ([url isEqualToString:@""]||[textJS isEqualToString:@""]) {
  879. NSLog(@"空的情况");
  880. textJS = @"hiddenLoading()";
  881. methodJS = @"hiddenLoading";
  882. }
  883. NSDictionary *dict = @{@"jsStr":textJS,@"name":methodJS};
  884. [self performSelector:@selector(uploadJS:) withObject:dict afterDelay:1];
  885. }
  886. //获取到图片
  887. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
  888. {
  889. dispatch_async(dispatch_get_main_queue(), ^{
  890. [picker dismissViewControllerAnimated:YES completion:^{
  891. UIImage * img=[info objectForKey:UIImagePickerControllerEditedImage];
  892. NSData *data = UIImageJPEGRepresentation(img, 0.5);
  893. if (data!=nil) {
  894. [self uploadPic:data];
  895. }else{
  896. NSLog(@"data == nil");
  897. [self uploadUrl:@""];
  898. }
  899. }];
  900. });
  901. }
  902. -(void)uploadJS:(NSDictionary *)dict {
  903. [self isExitCallToJS:dict[@"jsStr"] withMethodName:dict[@"name"]];
  904. }
  905. -(NSString *)convertToJsonData:(NSDictionary *)dict {
  906. NSError *error;
  907. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
  908. NSString *jsonString;
  909. if (!jsonData) {
  910. NSLog(@"%@",error);
  911. }else{
  912. jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
  913. }
  914. NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
  915. NSRange range = {0,jsonString.length};
  916. //去掉字符串中的空格
  917. [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
  918. NSRange range2 = {0,mutStr.length};
  919. //去掉字符串中的换行符
  920. [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
  921. return mutStr;
  922. }
  923. -(void)addNoNetViews{
  924. kMainQueue(^{
  925. [self removeNoNetViews];
  926. self.noNetView = [NoNetView shareView];
  927. [self.view addSubview:self.noNetView];
  928. });
  929. }
  930. -(void)removeNoNetViews{
  931. if (self.noNetView ) {
  932. [self.noNetView removeFromSuperview];
  933. self.noNetView = nil;
  934. }
  935. }
  936. #pragma mark **** 通知相关方法
  937. // 点击通知 跳转到通知内url
  938. -(void)requestWebView:(NSNotification *)notification{
  939. NSDictionary * infoDict = [notification object];
  940. if (!infoDict) {
  941. return;
  942. }
  943. NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"url"]];
  944. if (urlStr) {
  945. //当前控制器
  946. if(self.tabBarController.selectedIndex != 1) {
  947. return;
  948. }
  949. [[LXViewControllerManager shareViewControllerManager] showHudText:nil];
  950. [self performSelector:@selector(requestWebTime:) withObject:infoDict afterDelay:1];
  951. }
  952. }
  953. -(void)clickSubNotiMethods:(NSNotification *)notification{
  954. NSDictionary * infoDict = [notification object][@"info"];
  955. if (!infoDict) {
  956. return;
  957. }
  958. NSLog(@"%@",infoDict);
  959. NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"url"]];
  960. if (urlStr) {
  961. if(self.tabBarController.selectedIndex == 1) {
  962. //刷新新订阅消息
  963. NSString *infoUrl = [NSString stringWithFormat:@"%@%@", kHost, urlStr];
  964. infoUrl = [infoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  965. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:infoUrl]]];
  966. }
  967. }
  968. }
  969. //点击支付通知
  970. -(void)clickPayMethods:(NSNotification *)notification{
  971. NSDictionary * infoDict = [notification object][@"info"];
  972. if (!infoDict) {
  973. return;
  974. }
  975. NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"url"]];
  976. NSArray * array = [urlStr componentsSeparatedByString:@"=="];
  977. urlStr = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  978. NSString * titleStr = @"消息通知";
  979. titleStr = [NSString stringWithFormat:@"%@",infoDict[@"title"]];
  980. if (urlStr) {
  981. if(self.tabBarController.selectedIndex == 1) {
  982. [self JsOpenExternalLink:@{@"url":urlStr,@"title":titleStr}];
  983. }
  984. }
  985. }
  986. -(void)alipayWXpayStatus:(NSNotification *)notification{
  987. NSString * status = [notification object];
  988. [self performSelector:@selector(payStatus:) withObject:status afterDelay:2];
  989. }
  990. -(void)payStatus:(NSString *)status
  991. {
  992. //目前延时两秒
  993. NSLog(@"支付状态:%@",status);
  994. if(self.tabBarController.selectedIndex == 1) {
  995. [self isExitCallToJS:[NSString stringWithFormat:@"payCallBack('%@')", status] withMethodName:@"payCallBack"];
  996. }
  997. }
  998. // 调用js方法 刷新推送权限状态
  999. -(void)updateNotifyState{
  1000. if (self.updateNotify) {
  1001. self.updateNotify = NO;
  1002. [self isExitCallToJS:[NSString stringWithFormat:@"updateNoticeSwitch()"] withMethodName:@"updateNoticeSwitch"];
  1003. }
  1004. }
  1005. // 收到通知消息
  1006. -(void)afterReceiveNewMsg{
  1007. NSLog(@"afterReceiveNewMsg");
  1008. [self isExitCallToJS:@"afterReceiveNewMsg()" withMethodName:@"afterReceiveNewMsg"];
  1009. }
  1010. // 再次加载页面
  1011. -(void)reloadWebView{
  1012. if(self.tabBarController.selectedIndex == 1) {
  1013. [[LXViewControllerManager shareViewControllerManager] showHudText:nil];
  1014. if (!self.webView.canGoBack) {
  1015. [self webViewFirstRequest];
  1016. }else{
  1017. [self.webView reload];
  1018. }
  1019. }
  1020. }
  1021. // 收到退出登录消息
  1022. -(void)loginOut:(NSNotification *)notification{
  1023. if([notification.userInfo[@"item_index"] integerValue]!=1) {
  1024. return;
  1025. }
  1026. [self webViewRequestByMsg];
  1027. }
  1028. //收到消息退出并重新加载web
  1029. -(void)webViewRequestByMsg{
  1030. NSString *url = [NSString stringWithFormat:@"%@%@", kHost, @"jyapp/free/login?back=index&isios=t&flag=kicked"];
  1031. url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1032. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  1033. }
  1034. // 监控网络状态变化
  1035. -(void)netReachChanged:(NSNotification *)notificaition{
  1036. NSDictionary *userInfo = notificaition.userInfo;
  1037. if ([userInfo[@"AFNetworkingReachabilityNotificationStatusItem"] intValue] == 0 || [userInfo[@"AFNetworkingReachabilityNotificationStatusItem"] intValue] == -1) {
  1038. [self addNoNetViews];
  1039. }else{
  1040. [self removeNoNetViews];
  1041. }
  1042. }
  1043. -(void)newsRedPoint:(NSNotification *)notificaition
  1044. {
  1045. NSDictionary *dict = notificaition.userInfo;
  1046. if(self.tabBarController.selectedIndex == 1) {
  1047. NSString *textJS = [NSString stringWithFormat:@"afterReceivePushMessage('%@','%@')",dict[@"typeMsg"],dict[@"url"]];
  1048. [self isExitCallToJS:textJS withMethodName:@"afterReceivePushMessage"];
  1049. }
  1050. }
  1051. //刷新页面相关
  1052. -(void)refreshNonCurVC:(NSNotification *)notificaition{
  1053. if(self.tabBarController.selectedIndex != 1) {
  1054. [self webViewFirstRequest];
  1055. }
  1056. }
  1057. //通知刷新页面
  1058. -(void)refreshDY:(NSNotification *)notificaition{
  1059. NSDictionary *infoDict = notificaition.userInfo;
  1060. NSLog(@"%@",infoDict);
  1061. if (!infoDict) {
  1062. [self webViewFirstRequest];
  1063. }else {
  1064. NSString *infoUrl = [NSString stringWithFormat:@"%@%@", kHost, infoDict[@"url"]];
  1065. infoUrl = [infoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1066. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:infoUrl]]];
  1067. }
  1068. }
  1069. -(void)clearWeb{
  1070. NSURLCache * cache = [NSURLCache sharedURLCache];
  1071. [cache removeAllCachedResponses];
  1072. [cache setDiskCapacity:0];
  1073. [cache setMemoryCapacity:0];
  1074. }
  1075. /*
  1076. #pragma mark - Navigation
  1077. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1078. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1079. // Get the new view controller using [segue destinationViewController].
  1080. // Pass the selected object to the new view controller.
  1081. }
  1082. */
  1083. @end