JYNewExpViewController.m 49 KB

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