JYNewSubViewController.m 50 KB

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