JYNewMineViewController.m 50 KB

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