JYNewExpViewController.m 49 KB

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