JYNewSearchViewController.m 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  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 "JYNewSearchViewController.h"
  9. #import <WebKit/WebKit.h>
  10. #import "JYTabBarController.h"
  11. #import <CoreLocation/CoreLocation.h>
  12. @interface JYNewSearchViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,CLLocationManagerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,CLLocationManagerDelegate,SKProductsRequestDelegate,SKPaymentTransactionObserver>
  13. {
  14. NSInteger _timeTick;
  15. NSInteger _time;
  16. NSInteger pushIndex;//第几个模块过来的
  17. BOOL notiFinish;
  18. BOOL isLoadRedDot;
  19. CGPoint startTouch;
  20. BOOL _isMoving;
  21. }
  22. @property (nonatomic, strong) UIProgressView *progressView;
  23. @property (nonatomic, strong) WKWebView *webView;
  24. @property (nonatomic, strong)NSMutableDictionary *notiDict;
  25. @property (nonatomic,weak)NSTimer *timer;
  26. @property(nonatomic, assign)BOOL updateNotify;
  27. @property(nonatomic,strong)CLLocationManager *locaationManager;
  28. @property(nonatomic,strong)NSString *placeAdr;
  29. @property(nonatomic,assign)BOOL isLocation;
  30. @property(nonatomic, strong)NoNetView *noNetView;
  31. @property(nonatomic, strong)UIPanGestureRecognizer *recognizer;
  32. @end
  33. NSString *const new_kInitVector_1 = @"1389461544135476";
  34. size_t const new_kKeySize_1 = kCCKeySizeAES128;
  35. NSString *const new_AesKey_1 = @"mGlAgnIBB8bx2nch";
  36. @implementation JYNewSearchViewController
  37. -(void)viewWillAppear:(BOOL)animated
  38. {
  39. [super viewWillAppear:animated];
  40. [self.navigationController setNavigationBarHidden:YES animated:animated];
  41. }
  42. //进度条
  43. - (UIProgressView *)progressView
  44. {
  45. if (_progressView == nil) {
  46. _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,STATUS_BAR_HEIGHT - 2,WIDTH,2)];
  47. _progressView.tintColor = [UIColor blueColor];
  48. _progressView.trackTintColor = [UIColor whiteColor];
  49. }
  50. return _progressView;
  51. }
  52. //懒加载
  53. - (WKWebView *)webView
  54. {
  55. if(_webView == nil) {
  56. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  57. config.preferences = [[WKPreferences alloc] init];
  58. config.preferences.minimumFontSize = 0;
  59. config.allowsInlineMediaPlayback = YES;
  60. config.preferences.javaScriptEnabled = YES;
  61. config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
  62. //添加消息处理,注意:self指代的是需要遵守WKScriptMessageHandler协议,结束时需要移除
  63. config.userContentController = [[WKUserContentController alloc] init];
  64. //声明协议
  65. NSArray *jsArr = @[@"loginByWeixin",
  66. @"share",
  67. @"saveUserToken",
  68. @"removeUserToken",
  69. @"openSystemNotification",
  70. @"openExternalLink",
  71. @"alert",
  72. @"hiddenBottom",
  73. @"checkLab",
  74. @"loginSuccess",
  75. @"backUrl",
  76. @"clearPushMessage",
  77. @"hideRedSpotOnMenu",
  78. @"showRedSpotOnMenu",
  79. @"wxPay",
  80. @"aliPay",
  81. @"chooseTab",
  82. @"skipCamera",
  83. @"skipAlbum",
  84. @"openActivityPage",
  85. @"callPhone",
  86. @"openOtherAppLinks",
  87. @"inPurchasingVip",
  88. ];
  89. for (NSString*jsName in jsArr) {
  90. [config.userContentController addScriptMessageHandler:self name:jsName];
  91. }
  92. //高端的自定义配置创建WKWebView
  93. if (iPhoneX) {
  94. _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-TAB_BAR_HEIGHT) configuration:config];
  95. if (@available(iOS 11.0, *)) {
  96. _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  97. }
  98. }else {
  99. _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT-TAB_BAR_HEIGHT+STATUS_BAR_HEIGHT) configuration:config];
  100. }
  101. _webView.scrollView.bounces = NO;
  102. _webView.UIDelegate = self;
  103. _webView.navigationDelegate = self;
  104. _webView.userInteractionEnabled = YES;
  105. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  106. }
  107. return _webView;
  108. }
  109. -(void)webViewFirstRequest
  110. {
  111. //去时间戳-拼接
  112. NSString *url = [NSString stringWithFormat:@"%@jyapp/free/index?deviceid=%@", kHost, [LXUserDefaults getDeviceID]];
  113. NSString *token = [LXUserDefaults token];
  114. if ([LXUserDefaults isExistToken]) {
  115. url = [url stringByAppendingString:[NSString stringWithFormat:@"?sign=%@&url=/jyapp/jylab/mainSearch&from=restart", token]];
  116. }
  117. // NSLog(@"111 :第一次加载:%@",url);
  118. url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  119. kMainQueue(^{
  120. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  121. })
  122. }
  123. #pragma mark - event response
  124. // 计算wkWebView进度条
  125. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  126. if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
  127. CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
  128. self.progressView.alpha = 1.0f;
  129. [self.progressView setProgress:newprogress animated:YES];
  130. if (newprogress >= 1.0f) {
  131. self.recognizer.enabled = YES;
  132. [UIView animateWithDuration:0.3f
  133. delay:0.3f
  134. options:UIViewAnimationOptionCurveEaseOut
  135. animations:^{
  136. self.progressView.alpha = 0.0f;
  137. }
  138. completion:^(BOOL finished) {
  139. [self.progressView setProgress:0 animated:NO];
  140. }];
  141. }
  142. } else {
  143. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  144. }
  145. }
  146. -(void)initNotification {
  147. //加载通知
  148. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestWebView:) name:kRequestWebViewWithUrl object:nil];
  149. //点击订阅通知
  150. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickSubNotiMethods:) name:ClickSubNotiMethods object:nil];
  151. //点击支付通知
  152. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickPayMethods:) name:ClickPayMethods object:nil];
  153. //支付状态通知
  154. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayWXpayStatus:) name:AlipayWXpayStatus object:nil];
  155. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotifyState) name:kUpdateNotifyState object:nil];
  156. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(afterReceiveNewMsg) name:kAfterReceiveNewMsg object:nil];
  157. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadWebView) name:kReloadWebVIew object:nil];
  158. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOut:) name:kLoginOut object:nil];
  159. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netReachChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
  160. //前往登录通知-tabbar
  161. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isLoginTabBar:) name:LoginIndexTabBar object:nil];
  162. //展示底部红的通知
  163. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsRedPoint:) name:JYNewsRedPoint object:nil];
  164. //接收全新通知
  165. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshNonCurVC:) name:RefreshNonCurVC object:nil];
  166. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAllVC:) name:RefreshAllVC object:nil];
  167. }
  168. #pragma mark – Gesture Recognizer –
  169. -(void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
  170. {
  171. NSString *current_url = [self stringByEvaluatingJavaScriptFromString:@"document.location.href"];
  172. NSLog(@"%@",current_url);
  173. CGRect rect = self.view.bounds;
  174. CGFloat width = CGRectGetWidth(rect);
  175. if (![self.webView canGoBack]||([current_url containsString:@"jyapp/free/login"])) {
  176. NSLog(@"不可返回");
  177. return;
  178. }
  179. 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]]){
  180. return;
  181. }
  182. CGPoint touchPoint = [recoginzer locationInView:[UIApplication sharedApplication].keyWindow];
  183. if (recoginzer.state==UIGestureRecognizerStateBegan) {
  184. _isMoving = YES;
  185. startTouch = touchPoint;
  186. } else if (recoginzer.state==UIGestureRecognizerStateEnded||(recoginzer.state==UIGestureRecognizerStatePossible)){
  187. if (touchPoint.x - startTouch.x > width*0.125) {
  188. [UIView animateWithDuration:0.3 animations:^{
  189. [self moveViewWithX:width];
  190. if ([current_url containsString:@"jyapp/jylab/mainSearch#"]) {
  191. [self isExitCallToJS:@"afterClickBack()" withMethodName:@"afterClickBack"];
  192. }
  193. // [self.webView goBack];
  194. NSString *jsStr = @"window.history.back()";
  195. [self executeCallJS:jsStr];
  196. } completion:^(BOOL finished) {
  197. _isMoving = NO;
  198. [self moveViewWithX:0];
  199. }];
  200. } else {
  201. [UIView animateWithDuration:0.3 animations:^{
  202. [self moveViewWithX:0];
  203. } completion:^(BOOL finished) {
  204. _isMoving = NO;
  205. }];
  206. }
  207. return;
  208. } else if (recoginzer.state==UIGestureRecognizerStateCancelled){
  209. [UIView animateWithDuration:0.3 animations:^{
  210. [self moveViewWithX:0];
  211. } completion:^(BOOL finished) {
  212. _isMoving = NO;
  213. }];
  214. return;
  215. }else {
  216. }
  217. if (_isMoving) {
  218. [self moveViewWithX:touchPoint.x - startTouch.x];
  219. }
  220. }
  221. -(void)moveViewWithX:(float)x
  222. {
  223. CGRect rect = self.view.bounds;
  224. CGFloat width = CGRectGetWidth(rect);
  225. x = x>width?width:x;
  226. x = x<0?0:x;
  227. CGRect frame = self.webView.frame;
  228. frame.origin.x = x;
  229. self.webView.frame = frame;
  230. }
  231. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
  232. // message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
  233. // NSLog(@"原生收到了js发送过来的消息message.name = %@ message.body = %@",message.name,message.body);
  234. if ([message.name isEqualToString:@"loginByWeixin"]) {
  235. [self jsLoginByWeixin:message.body];
  236. }else if ([message.name isEqualToString:@"share"]) {
  237. [self jsShare:message.body];
  238. }else if ([message.name isEqualToString:@"saveUserToken"]) {
  239. [self jsSaveUserToken:message.body];
  240. }else if ([message.name isEqualToString:@"removeUserToken"]) {
  241. [self jsRemoveUserToken:message.body];
  242. }else if ([message.name isEqualToString:@"openSystemNotification"]) {
  243. [self jsOpenSystemNotification:message.body];
  244. }else if ([message.name isEqualToString:@"openExternalLink"]) {
  245. [self JsOpenExternalLink:message.body];
  246. }else if ([message.name isEqualToString:@"alert"]) {
  247. [self jsAlert:message.body];
  248. }else if ([message.name isEqualToString:@"hiddenBottom"]) {
  249. [self jsHiddenBottom:message.body];
  250. }else if ([message.name isEqualToString:@"checkLab"]) {
  251. [self jsCheckLab:message.body];
  252. }else if ([message.name isEqualToString:@"loginSuccess"]) {
  253. [self jsLoginSuccess:message.body];
  254. }else if ([message.name isEqualToString:@"backUrl"]) {
  255. [self jsBackUrl:message.body];
  256. }else if ([message.name isEqualToString:@"clearPushMessage"]) {
  257. [self jsClearPushMessage:message.body];
  258. }else if ([message.name isEqualToString:@"hideRedSpotOnMenu"]) {
  259. [self jsHideRedSpotOnMenu:message.body];
  260. }else if ([message.name isEqualToString:@"showRedSpotOnMenu"]) {
  261. [self jsShowRedSpotOnMenu:message.body];
  262. }else if ([message.name isEqualToString:@"wxPay"]) {
  263. [self jsWxPay:message.body];
  264. }else if ([message.name isEqualToString:@"aliPay"]) {
  265. [self jsAliPay:message.body];
  266. }else if ([message.name isEqualToString:@"chooseTab"]) {
  267. [self jsChooseTab:message.body];
  268. }else if ([message.name isEqualToString:@"skipCamera"]) {
  269. [self jsSkipCamera:message.body];
  270. }else if ([message.name isEqualToString:@"skipAlbum"]) {
  271. [self jsSkipAlbum:message.body];
  272. }else if ([message.name isEqualToString:@"openActivityPage"]) {
  273. [self jsOpenActivityPage:message.body];
  274. }else if ([message.name isEqualToString:@"callPhone"]) {
  275. [self jsCallPhone:message.body];
  276. }else if ([message.name isEqualToString:@"openOtherAppLinks"]) {
  277. [self jsOpenOtherAppLinks:message.body];
  278. }else if ([message.name isEqualToString:@"inPurchasingVip"]) {
  279. [self jsInPurchasingVip:message.body];
  280. }else {
  281. }
  282. }
  283. #pragma mark - WKUIDelegate
  284. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
  285. {
  286. NSError *err = nil;
  287. NSData *dataFromString = [prompt dataUsingEncoding:NSUTF8StringEncoding];
  288. NSDictionary *paramdict = [NSJSONSerialization JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:&err];
  289. // NSLog(@"拦截prompt:%@",paramdict);
  290. if (!err){
  291. NSString *type = [paramdict objectForKey:@"jsName"];
  292. if (type && [type isEqualToString:@"getUserToken"]) {
  293. NSDictionary *dict = @{@"type":@"string",
  294. @"value":[self jsGetUserToken:paramdict]};
  295. completionHandler([self convertToJsonData:dict]);
  296. }else if (type && [type isEqualToString:@"getVersion"]) {
  297. NSDictionary *dict = @{@"type":@"string",
  298. @"value":[self jsGetVersion:paramdict]};
  299. completionHandler([self convertToJsonData:dict]);
  300. }else if (type && [type isEqualToString:@"checkNoticePermission"]) {
  301. NSDictionary *dict = @{@"type":@"int",
  302. @"value":[NSString stringWithFormat:@"%d",[self jsCheckNoticePermission:paramdict]]};
  303. completionHandler([self convertToJsonData:dict]);
  304. }else if (type && [type isEqualToString:@"getPushRid"]) {
  305. NSDictionary *dict = @{@"type":@"string",@"value":[self jsGetPushRid:paramdict]};
  306. completionHandler([self convertToJsonData:dict]);
  307. }else if (type && [type isEqualToString:@"isInstallWeixin"]) {
  308. NSDictionary *dict = @{@"type":@"int",
  309. @"value":[NSString stringWithFormat:@"%d",[self jsIsInstallWeixin:paramdict]]};
  310. completionHandler([self convertToJsonData:dict]);
  311. }else if (type && [type isEqualToString:@"getCipherText"]) {
  312. NSDictionary *dict = @{@"type":@"string",
  313. @"value":[self jsGetCipherText:paramdict]};
  314. completionHandler([self convertToJsonData:dict]);
  315. }
  316. else if (type && [type isEqualToString:@"getOtherPushRid"]) {
  317. NSDictionary *dict = @{@"type":@"string",@"value":[self jsGetOtherPushRid:paramdict]};
  318. completionHandler([self convertToJsonData:dict]);
  319. }else if (type && [type isEqualToString:@"getPhoneBrand"]) {
  320. NSDictionary *dict = @{@"type":@"string",
  321. @"value":[self jsGetPhoneBrand:paramdict]};
  322. completionHandler([self convertToJsonData:dict]);
  323. }else if (type && [type isEqualToString:@"getLocation"]) {
  324. NSDictionary *dict = @{@"type":@"string",
  325. @"value":[self jsGetLocation:paramdict]};
  326. completionHandler([self convertToJsonData:dict]);
  327. }else {
  328. completionHandler(@"");
  329. }
  330. }
  331. }
  332. // 在发送请求之前,决定是否跳转
  333. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  334. //如果当前页面是三级页面-
  335. NSString *curUrl = [webView.URL absoluteString];
  336. if ([curUrl containsString:@"jyapp/article/content"]) {
  337. //当前页面是三级页面--判断待跳转页面是否符合内置跳转
  338. NSString *nextUrl = [navigationAction.request.URL absoluteString];
  339. if ([nextUrl containsString:@"jianyu360.com"]||[nextUrl containsString:@"jianyu360.cn"]||[nextUrl containsString:@"qmx.top"]) {
  340. // 允许跳转
  341. decisionHandler(WKNavigationActionPolicyAllow);
  342. }else {
  343. NSLog(@"不允许内部跳转:-%@",nextUrl);
  344. //筛选拦截-压缩包等格式不允许跳转
  345. if ([nextUrl hasSuffix:@".rar"]||[nextUrl hasSuffix:@".zip"]||[nextUrl hasSuffix:@".7z"]||[nextUrl hasSuffix:@".CAB"]||[nextUrl hasSuffix:@".ARJ"]||[nextUrl hasSuffix:@".LZH"]||[nextUrl hasSuffix:@".TAR"]||[nextUrl hasSuffix:@".GZ"]||[nextUrl hasSuffix:@".ACE"]||[nextUrl hasSuffix:@".UUE"]||[nextUrl hasSuffix:@".BZ2"]||[nextUrl hasSuffix:@".JAR"]||[nextUrl hasSuffix:@".ISO"]) {
  346. // 不允许跳转
  347. decisionHandler(WKNavigationActionPolicyCancel);
  348. }else {
  349. JYNewWebController *ctr = [[JYNewWebController alloc] init];
  350. ctr.url = nextUrl;
  351. ctr.titleShow = @"公告信息";
  352. kMainQueue(^{
  353. [self presentViewController:ctr animated:NO completion:nil];
  354. });
  355. // 不允许跳转-并跳转新页面
  356. decisionHandler(WKNavigationActionPolicyCancel);
  357. }
  358. }
  359. }else {
  360. // 允许跳转
  361. decisionHandler(WKNavigationActionPolicyAllow);
  362. }
  363. }
  364. #pragma mark ****WKUIDelegate
  365. //通过js alert 显示一个警告面板,调用原生会走此方法。
  366. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  367. {
  368. // NSLog(@"显示一个JavaScript警告面板, message = %@",message);
  369. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
  370. [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  371. completionHandler();
  372. }]];
  373. [self presentViewController:alertController animated:YES completion:nil];
  374. }
  375. //通过 js confirm 显示一个确认面板,调用原生会走此方法。
  376. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
  377. {
  378. // NSLog(@"运行JavaScript确认面板, message = %@", message);
  379. UIAlertController *action = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
  380. [action addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  381. completionHandler(NO);
  382. }] ];
  383. [action addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  384. completionHandler(YES);
  385. }]];
  386. [self presentViewController:action animated:YES completion:nil];
  387. }
  388. #pragma mark - OC调JS交互
  389. -(void)isExitCallToJS:(NSString *)jsStr withMethodName:(NSString *)name{
  390. NSString *jsName = [NSString stringWithFormat:@"function exist(){return !window['%@']};exist()",name];
  391. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  392. [_webView evaluateJavaScript:jsName completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  393. // NSLog(@"是否存在 result:%@,error:%@",result,error);
  394. if ([result intValue]==0) {
  395. [self executeCallJS:jsStr];
  396. }else {
  397. NSLog(@"不存在-不存在-不存在-%@",jsStr);
  398. }
  399. }];
  400. });
  401. }
  402. -(void)executeCallJS:(NSString *)jsStr {
  403. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  404. // NSLog(@"OC调JS交互%@:",jsStr);
  405. [_webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  406. if (error!=nil) {
  407. NSLog(@"result:%@,error:%@",result,error);
  408. [[GlobalData shareInstance] addOnePlistData:@{
  409. @"detail":[[self stringByEvaluatingJavaScriptFromString:@"document.location.href"] stringByAppendingString:[NSString stringWithFormat:@"\nJS异常方法:%@\n%@",jsStr,[error description]]],
  410. @"reqTime":[NSNumber numberWithInt:0],
  411. }];
  412. [[LXViewControllerManager shareViewControllerManager]showAlertViewWithMessage: jsStr];
  413. }
  414. }];
  415. });
  416. }
  417. - (void)viewDidLoad {
  418. [super viewDidLoad];
  419. // Do any additional setup after loading the view.
  420. NSLog(@"首页初始化");
  421. self.view.backgroundColor = [UIColor whiteColor];
  422. [self.view addSubview:self.webView];
  423. [self.view addSubview:self.progressView];
  424. [self webViewFirstRequest];
  425. [[AFNetworkReachabilityManager sharedManager] startMonitoring];
  426. [self initApnsTimer];
  427. [self initNotification];
  428. self.recognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(paningGestureReceive:)];
  429. [self.recognizer delaysTouchesBegan];
  430. [self.view addGestureRecognizer:self.recognizer];
  431. //初始化临时属性
  432. self.placeAdr = [NSString new];
  433. //定时器-检测错误数据是否超过10个 发送
  434. [NSTimer scheduledTimerWithTimeInterval:180 target:self selector:@selector(errorLogListening) userInfo:nil repeats:YES];
  435. //监听底部栏
  436. [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(bottomOneListening) userInfo:nil repeats:YES];
  437. //监听购买结果
  438. [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
  439. }
  440. -(void)bottomOneListening {
  441. if(self.tabBarController.selectedIndex == 0) {
  442. [self judgeIsHiddenBottom];
  443. }
  444. }
  445. - (BOOL)isTheCurrentPeriod{
  446. NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  447. NSDate *now = [NSDate date];
  448. NSDateComponents *comps = [[NSDateComponents alloc] init];
  449. NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  450. comps = [calendar components:unitFlags fromDate:now];
  451. long hour = (long)[comps hour];
  452. if (hour>=12&&hour<14) {
  453. return YES;
  454. }
  455. if (hour>=17&&hour<=23) {
  456. return YES;
  457. }
  458. if (hour>=0&&hour<7) {
  459. return YES;
  460. }
  461. return NO;
  462. }
  463. - (NSString *)toJsonStrWithArray:(NSArray *)arr {
  464. if ([arr isKindOfClass:[NSString class]]) {
  465. return (NSString *)arr;
  466. }
  467. NSError *parseError = nil;
  468. NSData *data = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
  469. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  470. jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  471. jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
  472. jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  473. if (parseError) {
  474. jsonStr = @"";
  475. }
  476. return jsonStr;
  477. }
  478. -(void)errorLogListening {
  479. if ([self isTheCurrentPeriod]) {
  480. if ([[GlobalData shareInstance] getPlistCount]>=50) {
  481. NSMutableDictionary *dict =[[GlobalData shareInstance] getPlistAllData];
  482. [[LXNetworkManager shareLXNetworkManager]postWithURLStr:[NSString stringWithFormat:@"%@jyapp/errLogs/Receive",kHost] parameters:@{@"jsonData":[self toJsonStrWithArray:dict[@"jsonData"]]} progress:^(NSProgress *progress) {
  483. NSLog(@"%@",progress);
  484. } success:^(id responseObject) {
  485. NSLog(@"responseObject=%@",responseObject);
  486. [[GlobalData shareInstance] clearPlistData];
  487. } failure:^(NSError *error) {
  488. NSLog(@"error=%@",error);
  489. [[GlobalData shareInstance] addOnePlistData:@{
  490. @"detail":[NSString stringWithFormat:@"上传日志接口:%@",[error description]],
  491. @"reqTime":[NSNumber numberWithInt:0],
  492. }];
  493. }];
  494. }
  495. }else {
  496. }
  497. }
  498. -(void)initApnsTimer {
  499. //定时器
  500. if([LXUserDefaults isExistToken]) {
  501. self.notiDict = [[NSMutableDictionary alloc]initWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:RemoteNotifications]];
  502. if(self.notiDict.count) {
  503. self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
  504. }
  505. }
  506. }
  507. -(void)haveRedPoint
  508. {
  509. NSLog(@"http请求-------小红点");
  510. NSString *token = [LXUserDefaults token];
  511. if ([LXUserDefaults isExistToken]) {
  512. [[LXNetworkManager shareLXNetworkManager]postWithURLStr:[NSString stringWithFormat:@"%@jyapp/free/showRedSpotOnMenu",kHost] parameters:@{@"token":token} progress:^(NSProgress *progress) {
  513. // NSLog(@"%@",progress);
  514. } success:^(id responseObject) {
  515. // NSLog(@"responseObject=%@",responseObject);
  516. if([responseObject[@"subscribe"] integerValue]>=1) {
  517. //显示
  518. [GlobalData shareInstance].subIsRed = YES;
  519. kMainQueue(^{
  520. [self.tabBarController.tabBar showBadgeOnItemIndex:1];
  521. });
  522. }else {
  523. [GlobalData shareInstance].subIsRed = NO;
  524. kMainQueue(^{
  525. [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
  526. });
  527. }
  528. if([responseObject[@"my"] integerValue]>=1) {
  529. //显示
  530. [GlobalData shareInstance].mineIsRed = YES;
  531. kMainQueue(^{
  532. [self.tabBarController.tabBar showBadgeOnItemIndex:3];
  533. });
  534. }else {
  535. [GlobalData shareInstance].mineIsRed = NO;
  536. kMainQueue(^{
  537. [self.tabBarController.tabBar hideBadgeOnItemIndex:3];
  538. });
  539. }
  540. } failure:^(NSError *error) {
  541. NSLog(@"error=%@",error);
  542. [[GlobalData shareInstance] addOnePlistData:@{
  543. @"detail":[NSString stringWithFormat:@"获取小红点接口:%@",[error description]],
  544. @"reqTime":[NSNumber numberWithInt:0],
  545. }];
  546. }];
  547. }
  548. }
  549. #pragma mark - WKNavigationDelegate
  550. /* 页面加载完成 */
  551. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
  552. // NSLog(@"-----页面加载完成%@",webView.URL.absoluteString);
  553. //第一次加载小红点
  554. if(!isLoadRedDot) {
  555. isLoadRedDot = true;
  556. [self haveRedPoint];
  557. }
  558. if(!notiFinish) {
  559. notiFinish = YES;
  560. }
  561. [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
  562. [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
  563. [self judgeIsHiddenBottom];//是否隐藏
  564. [self removeNoNetViews];
  565. [[LXViewControllerManager shareViewControllerManager] hideHud];
  566. //写数据
  567. // [self writeWKWebData:webView.URL];
  568. }
  569. -(void)writeWKWebData:(NSURL *)url {
  570. //得到NSData 数据
  571. NSData *dataContent = [NSData dataWithContentsOfURL:url];
  572. //NSURLCache 实例化
  573. NSURLCache *cache = [NSURLCache sharedURLCache];
  574. //得到相应
  575. NSURLResponse *response = [[NSURLResponse alloc]initWithURL:url MIMEType:nil expectedContentLength:0 textEncodingName:@"UTF-8"];
  576. //得到CacheURLResponse
  577. NSCachedURLResponse *cacheResponse = [[NSCachedURLResponse alloc]initWithResponse:response data:dataContent];
  578. //进行存储
  579. [cache storeCachedResponse:cacheResponse forRequest:[NSURLRequest requestWithURL:url]];
  580. }
  581. // 页面开始加载时调用
  582. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
  583. self.recognizer.enabled = NO;
  584. }
  585. // 当内容开始返回时调用
  586. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
  587. }
  588. // 页面加载失败时调用
  589. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(nonnull NSError *)error{
  590. self.recognizer.enabled = YES;
  591. [[GlobalData shareInstance] addOnePlistData:@{
  592. @"detail":[[self stringByEvaluatingJavaScriptFromString:@"document.location.href"] stringByAppendingString:[NSString stringWithFormat:@"\n%@",[error description]]],
  593. @"reqTime":[NSNumber numberWithInt:0],
  594. }];
  595. }
  596. #pragma mark *****JS与OC交互
  597. #pragma mark - WKScriptMessageHandler JS调OC交互
  598. -(void)jsLoginByWeixin:(NSDictionary *)dict {
  599. if ([LXUserDefaults isInstallWeiXin] != 1) { // 没有安装微信 不走友盟
  600. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"微信登录失败,没有安装微信" delay:1.5];
  601. return;
  602. }
  603. [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error) {
  604. UMSocialUserInfoResponse *resp = result;
  605. [self dealWXDic:(NSDictionary *)resp.originalResponse];
  606. }];
  607. }
  608. // 处理微信登录获取到的数据
  609. -(void)dealWXDic:(NSDictionary *)dictionary{
  610. //如果获取到用户信息,即用户点击了“登录”,则进行用户信息获取
  611. if (dictionary.count > 0) {
  612. NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:dictionary];
  613. if (dic) {
  614. [dic removeObjectForKey:@"privilege"];
  615. [dic removeObjectForKey:@"language"];
  616. double currDouble = [[NSDate date] timeIntervalSince1970];
  617. [dic setObject:[NSNumber numberWithLong:(long)currDouble] forKey:@"createtime"];
  618. // 拼接标志位
  619. 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"]];
  620. sign = [LXMD5 md532BitLower:sign];
  621. [dic setObject:sign forKey:@"sign"];
  622. NSString *endStr = [[LXViewControllerManager shareViewControllerManager] getJsonStr:dic];
  623. NSData *data = [endStr dataUsingEncoding:NSUTF8StringEncoding];
  624. endStr = [data base64EncodedStringWithOptions:0];
  625. [self isExitCallToJS:[NSString stringWithFormat:@"loginByWeixinCallBack('%@')", endStr] withMethodName:@"loginByWeixinCallBack"];
  626. }
  627. }
  628. }
  629. -(void)jsShare:(NSDictionary *)dict {
  630. NSString *type = [NSString stringWithFormat:@"%@",dict[@"type"]];
  631. NSString *title = [NSString stringWithFormat:@"%@",dict[@"title"]];
  632. NSString *content = [NSString stringWithFormat:@"%@",dict[@"content"]];
  633. NSString *link = [NSString stringWithFormat:@"%@",dict[@"link"]];
  634. UMSocialPlatformType shareType;
  635. if ([type intValue] == 1) { // 微信好友
  636. shareType = UMSocialPlatformType_WechatSession;
  637. }else if ([type intValue] == 2){ /// qq好友
  638. shareType = UMSocialPlatformType_QQ;
  639. }else if ([type intValue] == 3){ // 朋友圈
  640. shareType = UMSocialPlatformType_WechatTimeLine;
  641. }else{
  642. shareType = UMSocialPlatformType_WechatSession;
  643. }
  644. if ([type intValue] == 1 || [type intValue] == 3) {
  645. if ([LXUserDefaults isInstallWeiXin] != 1) {
  646. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"没有安装微信" delay:1.5];
  647. return;
  648. }
  649. }
  650. if ([type intValue] == 2) {
  651. if (![[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_QQ]) {
  652. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"没有安装QQ" delay:1.5];
  653. return;
  654. }
  655. }
  656. //创建分享消息对象
  657. UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
  658. //创建网页内容对象
  659. UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:content thumImage:[UIImage imageNamed:@"logo"]];
  660. //设置网页地址
  661. shareObject.webpageUrl = link;
  662. messageObject.shareObject = shareObject;
  663. //调用分享接口
  664. [[UMSocialManager defaultManager] shareToPlatform:shareType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
  665. if (error) {
  666. if (error.userInfo[@"message"] && [error.userInfo[@"message"] containsString:@"Operation is cancel"]) {
  667. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"取消分享" delay:1];
  668. }else{
  669. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:error.userInfo[@"message"] delay:1];
  670. }
  671. [self isExitCallToJS:[NSString stringWithFormat:@"shareCallBack('%@','%@')",type,@"0"] withMethodName:@"shareCallBack"];
  672. }else{
  673. if ([data isKindOfClass:[UMSocialShareResponse class]]) {
  674. [self isExitCallToJS:[NSString stringWithFormat:@"shareCallBack('%@','%@')",type,@"1"] withMethodName:@"shareCallBack"];
  675. }else{
  676. UMSocialLogInfo(@"response data is %@",data);
  677. }
  678. }
  679. }];
  680. }
  681. -(void)jsSaveUserToken:(NSDictionary *)dict{
  682. [LXUserDefaults saveToken:[NSString stringWithFormat:@"%@",dict[@"token"]]];
  683. }
  684. -(NSString *)jsGetUserToken:(NSDictionary *)dict{
  685. return [LXUserDefaults token];
  686. }
  687. -(void)jsRemoveUserToken:(NSDictionary *)dict{
  688. [LXUserDefaults clearAll];
  689. }
  690. -(int)jsCheckNoticePermission:(NSDictionary *)dict{
  691. return [LXUserDefaults notifyState];
  692. }
  693. // 跳转到系统设置
  694. -(void)jsOpenSystemNotification:(NSDictionary *)dict{
  695. self.updateNotify = YES;
  696. [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  697. }
  698. // 获取推送id
  699. -(NSString *)jsGetPushRid:(NSDictionary *)dict{
  700. return [LXUserDefaults registrationID];
  701. }
  702. // 打开新页面 加载新web
  703. -(void)JsOpenExternalLink:(NSDictionary *)dict{
  704. NSString *url = [NSString stringWithFormat:@"%@",dict[@"url"]];
  705. NSString *title = [NSString stringWithFormat:@"%@",dict[@"title"]];
  706. if (url) {
  707. if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable || [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusUnknown) {
  708. }
  709. JYNewWebController *ctr = [[JYNewWebController alloc] init];
  710. ctr.url = url;
  711. if (!title || [title isEqualToString:@""] || [title isEqualToString:@"undefined"]) {
  712. ctr.titleShow = nil;
  713. }else{
  714. ctr.titleShow = title;
  715. }
  716. kMainQueue(^{
  717. [self presentViewController:ctr animated:NO completion:nil];
  718. });
  719. }
  720. }
  721. // 获取当前版本号
  722. -(NSString *)jsGetVersion:(NSDictionary *)dict{
  723. return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
  724. }
  725. -(void)jsAlert:(NSDictionary *)dict{
  726. [[LXViewControllerManager shareViewControllerManager] showAlertViewWithMessage:[NSString stringWithFormat:@"%@",dict[@"content"]]];
  727. }
  728. -(int)jsIsInstallWeixin:(NSDictionary *)dict{
  729. return [LXUserDefaults isInstallWeiXin];
  730. }
  731. -(NSString *)jsGetCipherText:(NSDictionary *)dict{
  732. NSDictionary *objDict = [NSDictionary dictionaryWithDictionary:dict[@"arguments"]];
  733. NSString *phone = [NSString stringWithFormat:@"%@",objDict[@"phone"]];
  734. NSDate *date=[NSDate date];
  735. NSDateFormatter *format1=[[NSDateFormatter alloc] init];
  736. [format1 setDateFormat:@"yyyyMMddhhmmss"];
  737. NSString *dateStr;
  738. dateStr=[format1 stringFromDate:date];
  739. NSLog(@"%@",dateStr);
  740. NSString *content = [[NSString stringWithFormat:@"%@_%@",phone,dateStr] stringByAppendingString:[NSString stringWithFormat:@"_%@",[LXMD5 md532BitLower:[NSString stringWithFormat:@"%@&%@",phone,dateStr]]]];
  741. NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
  742. NSUInteger dataLength = contentData.length;
  743. // 为结束符'\\0' +1
  744. char keyPtr[new_kKeySize_1 + 1];
  745. memset(keyPtr, 0, sizeof(keyPtr));
  746. [new_AesKey_1 getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
  747. // 密文长度 <= 明文长度 + BlockSize
  748. size_t encryptSize = dataLength + kCCBlockSizeAES128;
  749. void *encryptedBytes = malloc(encryptSize);
  750. size_t actualOutSize = 0;
  751. NSData *initVector = [new_kInitVector_1 dataUsingEncoding:NSUTF8StringEncoding];
  752. CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
  753. kCCAlgorithmAES,
  754. kCCOptionPKCS7Padding, // 系统默认使用 CBC,然后指明使用 PKCS7Padding
  755. keyPtr,
  756. new_kKeySize_1,
  757. initVector.bytes,
  758. contentData.bytes,
  759. dataLength,
  760. encryptedBytes,
  761. encryptSize,
  762. &actualOutSize);
  763. if (cryptStatus == kCCSuccess) {
  764. // 对加密后的数据进行 base64 编码
  765. return [[NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
  766. }
  767. free(encryptedBytes);
  768. return nil;
  769. }
  770. -(void)jsHiddenBottom:(NSDictionary *)dict{
  771. if(self.tabBarController.selectedIndex == 0) {
  772. if([[NSString stringWithFormat:@"%@",dict[@"hidden"]] integerValue]==0) {
  773. [self hideTabBar];
  774. [self hiddenMethodTabBar];
  775. }else {
  776. [self showTabBar];
  777. [self showMethodTabBar];
  778. }
  779. }
  780. }
  781. -(void)jsCheckLab:(NSDictionary *)dict {
  782. [[NSNotificationCenter defaultCenter] postNotificationName:RefreshNonCurVC object:nil userInfo:nil];
  783. }
  784. //js方法登录成功
  785. -(void)jsLoginSuccess:(NSDictionary *)dict {
  786. NSLog(@"search登录成功提示");
  787. NSString *status = [NSString stringWithFormat:@"%@",dict[@"status"]];
  788. [GlobalData shareInstance].isReLogin = YES;
  789. if([status isEqualToString:@"S"]) {
  790. if(pushIndex!=0) {
  791. kMainQueue((^{
  792. [[NSNotificationCenter defaultCenter] postNotificationName:RefreshAllVC object:nil userInfo:nil];
  793. AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  794. JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
  795. tab.selectedIndex = pushIndex;
  796. pushIndex = 0;
  797. }));
  798. }else {
  799. [self webViewFirstRequest];
  800. }
  801. }else if ([status isEqualToString:@""]) {
  802. //不刷新订阅-首页,刷新其他
  803. [[NSNotificationCenter defaultCenter] postNotificationName:RefreshExpAndMine object:nil userInfo:nil];
  804. }else {
  805. }
  806. }
  807. -(void)jsBackUrl:(NSDictionary *)dict {
  808. NSString *status = [NSString stringWithFormat:@"%@",dict[@"status"]];
  809. if([status isEqualToString:@"H"]) {
  810. pushIndex = 0;
  811. [self webViewFirstRequest];
  812. }
  813. }
  814. -(void)jsClearPushMessage:(NSDictionary *)dict {
  815. kMainQueue(^{
  816. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
  817. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
  818. });
  819. }
  820. -(void)jsHideRedSpotOnMenu:(NSDictionary *)dict {
  821. NSString *menu = [NSString stringWithFormat:@"%@",dict[@"menu"]];
  822. if([menu isEqualToString:@"subscribe"]) {
  823. kMainQueue(^{
  824. [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
  825. });
  826. }
  827. if([menu isEqualToString:@"my"]) {
  828. kMainQueue(^{
  829. [self.tabBarController.tabBar hideBadgeOnItemIndex:3];
  830. });
  831. }
  832. }
  833. -(void)jsShowRedSpotOnMenu:(NSDictionary *)dict {
  834. NSString *menu = [NSString stringWithFormat:@"%@",dict[@"menu"]];
  835. if([menu isEqualToString:@"subscribe"]) {
  836. kMainQueue(^{
  837. [self.tabBarController.tabBar showBadgeOnItemIndex:1];
  838. });
  839. }
  840. if([menu isEqualToString:@"my"]) {
  841. kMainQueue(^{
  842. [self.tabBarController.tabBar showBadgeOnItemIndex:3];
  843. });
  844. }
  845. }
  846. -(void)jsWxPay:(NSDictionary *)dict {
  847. NSString *jsonString = [NSString stringWithFormat:@"%@",dict[@"order"]];
  848. if ([LXUserDefaults isInstallWeiXin] != 1) { // 没有安装wx
  849. [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"请先安装微信再进行支付!" delay:1.5];
  850. return;
  851. }
  852. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  853. NSError *err;
  854. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
  855. if(err) {
  856. NSLog(@"json解析失败:%@",err);
  857. return;
  858. }
  859. //吊起微信
  860. PayReq *request = [[PayReq alloc] init] ;
  861. request.openID = dic[@"Appid"];
  862. request.partnerId = dic[@"Partnerid"];
  863. request.prepayId= dic[@"Prepayid"];
  864. request.package = @"Sign=WXPay";
  865. request.nonceStr= dic[@"Noncestr"];
  866. request.timeStamp= [dic[@"Timestamp"] intValue];
  867. request.sign= dic[@"Sign"];
  868. kMainQueue(^{
  869. [WXApi sendReq:request];
  870. });
  871. }
  872. -(void)jsAliPay:(NSDictionary *)dict {
  873. NSString *order = [NSString stringWithFormat:@"%@",dict[@"order"]];
  874. kMainQueue(^{
  875. [[AlipaySDK defaultService] payOrder:order fromScheme:@"jianyuiosapp" callback:nil];
  876. });
  877. }
  878. -(NSString *)jsGetOtherPushRid:(NSDictionary *)dict {
  879. return [LXUserDefaults deviceToken];
  880. }
  881. -(NSString *)jsGetPhoneBrand:(NSDictionary *)dict {
  882. UIDevice *device = [UIDevice currentDevice];
  883. return device.platformString;
  884. }
  885. -(NSString *)jsGetLocation:(NSDictionary *)dict {
  886. // NSLog(@"------开始调用获取位置:%@",self.placeAdr);
  887. if (!self.isLocation) {
  888. // 1.检查定位服务是否开启
  889. if ([self checkLocationServiceIsEnabled]) {
  890. // 2.创建定位管理器:
  891. NSLog(@"定位可用");
  892. [self createCLManager];
  893. self.isLocation = YES; //只请求一次
  894. }else{
  895. NSLog(@"定位不可用");
  896. self.isLocation = NO;
  897. }
  898. NSLog(@"即将返回城市信息-%@",self.placeAdr);
  899. }
  900. return self.placeAdr;
  901. }
  902. -(void)jsChooseTab:(NSDictionary *)dict {
  903. NSInteger indexTab = [dict[@"indexTab"] integerValue];
  904. kMainQueue((^{
  905. AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  906. JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
  907. tab.selectedIndex = indexTab;
  908. pushIndex = indexTab;
  909. }));
  910. }
  911. //拍照上传图片
  912. -(void)jsSkipCamera:(NSDictionary *)dict {
  913. UIImagePickerController *picker = [[UIImagePickerController alloc] init];
  914. picker.delegate = self;
  915. picker.allowsEditing = YES;
  916. picker.sourceType = UIImagePickerControllerSourceTypeCamera;
  917. dispatch_async(dispatch_get_main_queue(), ^{
  918. [self presentViewController:picker animated:YES completion:nil];
  919. });
  920. }
  921. //相册选择照片
  922. -(void)jsSkipAlbum:(NSDictionary *)dict {
  923. UIImagePickerController *picker = [[UIImagePickerController alloc] init];
  924. picker.delegate = self;
  925. picker.allowsEditing = YES;
  926. picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  927. dispatch_async(dispatch_get_main_queue(), ^{
  928. [self presentViewController:picker animated:YES completion:nil];
  929. });
  930. }
  931. //统计点击推送
  932. -(void)jsOpenActivityPage:(NSDictionary *)dict {
  933. NSDictionary * infoDic = @{@"url":[NSString stringWithFormat:@"%@",dict[@"url"]],
  934. @"rectype":[NSString stringWithFormat:@"%@",dict[@"rectype"]],
  935. @"openid":[NSString stringWithFormat:@"%@",dict[@"openid"]],
  936. };
  937. //post请求
  938. NSLog(@"%@",[NSString stringWithFormat:@"%@jyapp/free/message/receive",kHost]);
  939. [[LXNetworkManager shareLXNetworkManager]postWithURLStr:[NSString stringWithFormat:@"%@jyapp/free/message/receive",kHost] parameters:infoDic progress:^(NSProgress *progress) {
  940. NSLog(@"成功:%@",progress);
  941. } success:^(id responseObject) {
  942. NSLog(@"responseObject=%@",responseObject);
  943. } failure:^(NSError *error) {
  944. NSLog(@"error=%@",error);
  945. [[GlobalData shareInstance] addOnePlistData:@{
  946. @"detail":[NSString stringWithFormat:@"message/receive接口:%@",[error description]],
  947. @"reqTime":[NSNumber numberWithInt:0],
  948. }];
  949. }];
  950. }
  951. //拨打电话
  952. -(void)jsCallPhone:(NSDictionary *)dict {
  953. NSString *phone = [NSString stringWithFormat:@"%@",dict[@"phone"]];
  954. NSMutableString *tel = [[NSMutableString alloc]initWithFormat:@"telprompt://%@",phone];
  955. if (@available(iOS 10.0, *)) {
  956. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel] options:@{} completionHandler:^(BOOL success) {
  957. }];
  958. } else {
  959. // Fallback on earlier versions
  960. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel]];
  961. }
  962. }
  963. //打开其他app 抖音+快手
  964. -(void)jsOpenOtherAppLinks:(NSDictionary *)dict {
  965. //测试跳转抖音--快手 @"gifshow://" @"snssdk1128://"
  966. NSString *appLink = [NSString stringWithFormat:@"%@",dict[@"appLink"]];
  967. NSString *appName = [NSString stringWithFormat:@"%@",dict[@"appName"]];
  968. NSLog(@"appName:%@",appName);
  969. NSURL *url = [NSURL URLWithString:appLink];
  970. if ([[UIApplication sharedApplication] canOpenURL:url]) {
  971. if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
  972. //iOS 10.0+
  973. NSLog(@"iOS 10+");
  974. if (@available(iOS 10.0, *)) {
  975. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
  976. if (!success) {
  977. [[LXDataBaseManager shareDataBaseManager]showHudOnlyText:appName delay:2];
  978. }
  979. }];
  980. } else {
  981. // Fallback on earlier versions
  982. [[UIApplication sharedApplication] openURL:url];
  983. }
  984. }else{
  985. NSLog(@"iOS 2~10");
  986. //iOS 2~10
  987. [[UIApplication sharedApplication] openURL:url];
  988. }
  989. }else{
  990. //一般是没有安装
  991. NSLog(@"跳转下载app链接");
  992. [[LXDataBaseManager shareDataBaseManager]showHudOnlyText:appName delay:2];
  993. }
  994. }
  995. //内购VIP
  996. -(void)jsInPurchasingVip:(NSDictionary *)dict {
  997. NSString *productid = [NSString stringWithFormat:@"%@",dict[@"productid"]];
  998. //产品id
  999. if ([productid isEqualToString:@""]) {
  1000. NSLog(@"订单号 有问题");
  1001. [[LXDataBaseManager shareDataBaseManager]showHudOnlyText:@"订单号异常,请重试" delay:1];
  1002. return;
  1003. }
  1004. [[LXViewControllerManager shareViewControllerManager] showHudText:@"苹果验证中,请稍候"];
  1005. //监听购买结果
  1006. if([SKPaymentQueue canMakePayments]){
  1007. [self requestProductData:productid];
  1008. }else{
  1009. NSLog(@"不允许程序内付费");
  1010. [[LXViewControllerManager shareViewControllerManager] hideHud];
  1011. }
  1012. }
  1013. //去苹果服务器请求商品
  1014. - (void)requestProductData:(NSString *)type {
  1015. NSArray *product = [[NSArray alloc] initWithObjects:type,nil];
  1016. NSSet *nsset = [NSSet setWithArray:product];
  1017. SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
  1018. request.delegate = self;
  1019. [request start];
  1020. }
  1021. - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
  1022. NSArray *myProduct = response.products;
  1023. if (myProduct.count == 0) {
  1024. NSLog(@"无法获取产品信息,购买失败。");
  1025. [[LXViewControllerManager shareViewControllerManager]showHudOnlyText:@"暂时未获取到产品信息,请重试" delay:1];
  1026. return;
  1027. }
  1028. SKPayment * payment = [SKPayment paymentWithProduct:myProduct[0]];
  1029. [[SKPaymentQueue defaultQueue] addPayment:payment];
  1030. }
  1031. //监听购买结果
  1032. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
  1033. // NSLog(@"收到支付回调");
  1034. for (SKPaymentTransaction *transaction in transactions) {
  1035. switch (transaction.transactionState) {
  1036. case SKPaymentTransactionStatePurchased://交易完成
  1037. NSLog(@"购买成功transactionIdentifier = %@", transaction.transactionIdentifier);
  1038. [self completeTransaction:transaction];
  1039. break;
  1040. case SKPaymentTransactionStateFailed://交易失败
  1041. [self failedTransaction:transaction];
  1042. break;
  1043. case SKPaymentTransactionStateRestored://已经购买过该商品
  1044. [self restoreTransaction:transaction];
  1045. break;
  1046. case SKPaymentTransactionStatePurchasing://商品添加进列表
  1047. NSLog(@"商品添加进列表");
  1048. break;
  1049. default:
  1050. break;
  1051. }
  1052. }
  1053. }
  1054. - (void)completeTransaction:(SKPaymentTransaction *)transaction {
  1055. // Your application should implement these two methods.
  1056. [[LXViewControllerManager shareViewControllerManager] hideHud];
  1057. NSString * productIdentifier = transaction.payment.productIdentifier;
  1058. NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[[NSBundle mainBundle] appStoreReceiptURL]];
  1059. NSData *receiptData;
  1060. NSError *error = nil;
  1061. receiptData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&error];
  1062. NSString *receipt = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
  1063. if ([productIdentifier length] > 0) {
  1064. // 向自己的服务器验证购买凭证
  1065. if(self.tabBarController.selectedIndex == 0) {
  1066. [self isExitCallToJS:[NSString stringWithFormat:@"getReceipt('%@')", receipt] withMethodName:@"getReceipt"];
  1067. }else {
  1068. [[NSNotificationCenter defaultCenter] postNotificationName:@"receiptData" object:nil userInfo:@{@"receipt":receipt}];
  1069. }
  1070. }
  1071. // Remove the transaction from the payment queue.
  1072. [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
  1073. }
  1074. - (void)failedTransaction:(SKPaymentTransaction *)transaction {
  1075. [[LXViewControllerManager shareViewControllerManager] hideHud];
  1076. if(transaction.error.code != SKErrorPaymentCancelled) {
  1077. NSLog(@"购买失败");
  1078. [[LXViewControllerManager shareViewControllerManager]showHudOnlyText:@"购买失败,请重新尝试。" delay:1];
  1079. } else {
  1080. NSLog(@"用户取消交易");
  1081. [[LXViewControllerManager shareViewControllerManager]showHudOnlyText:@"取消交易" delay:1];
  1082. }
  1083. [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
  1084. }
  1085. - (void)restoreTransaction:(SKPaymentTransaction *)transaction {
  1086. // 对于已购商品,处理恢复购买的逻辑
  1087. NSLog(@"对于已购商品,处理恢复购买的逻辑");
  1088. [[LXViewControllerManager shareViewControllerManager] hideHud];
  1089. [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
  1090. }
  1091. // web是否可退回上页面
  1092. -(int)jsIsCanBack:(NSString *)str{
  1093. return self.webView.canGoBack ? 1:0;
  1094. }
  1095. #pragma mark *****其他方法
  1096. -(void)judgeIsHiddenBottom {
  1097. if(self.tabBarController.selectedIndex == 0) {
  1098. NSString *current_url = [self stringByEvaluatingJavaScriptFromString:@"document.location.href"];
  1099. NSArray *array = [current_url componentsSeparatedByString:@"?"];
  1100. current_url = [NSString stringWithFormat:@"%@",array.firstObject];
  1101. if([current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/jylab/mainSearch",kHost]]){
  1102. [self showTabBar];
  1103. [self showMethodTabBar];
  1104. }else {
  1105. [self hideTabBar];
  1106. [self hiddenMethodTabBar];
  1107. }
  1108. }
  1109. }
  1110. -(void)timeFireMethod{
  1111. _timeTick++;
  1112. if(self.webView&&notiFinish) {
  1113. NSString * urlStr = [NSString stringWithFormat:@"%@",self.notiDict[@"info"][@"url"]];
  1114. if (urlStr) {
  1115. if([self.notiDict[@"type"] isEqualToString:@"bid"]) {
  1116. AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1117. JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
  1118. tab.selectedIndex = 1;
  1119. [self performSelector:@selector(pushDY:) withObject:self.notiDict[@"info"] afterDelay:1];
  1120. }else {
  1121. [self performSelector:@selector(requestWebTime:) withObject:self.notiDict afterDelay:1];
  1122. }
  1123. [self.timer invalidate];
  1124. self.timer = nil;
  1125. _timeTick = 0;
  1126. [[NSUserDefaults standardUserDefaults] removeObjectForKey:RemoteNotifications];
  1127. }
  1128. return;
  1129. }
  1130. if (_timeTick == 60) {
  1131. [self.timer invalidate];
  1132. self.timer = nil;
  1133. _timeTick = 0;
  1134. [[NSUserDefaults standardUserDefaults] removeObjectForKey:RemoteNotifications];
  1135. }
  1136. }
  1137. -(void)pushDY:(NSDictionary *)infoDict
  1138. {
  1139. [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDY" object:nil userInfo:infoDict];
  1140. }
  1141. -(void)requestWebTime:(NSDictionary *)infoDict
  1142. {
  1143. NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"url"]];
  1144. if([infoDict[@"type"] isEqualToString:@"message"]) {
  1145. NSString *url = [NSString stringWithFormat:@"%@",urlStr];
  1146. NSArray * array = [url componentsSeparatedByString:@"=="];
  1147. url = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1148. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  1149. }else if ([infoDict[@"type"] isEqualToString:@"titleMessage"]) {
  1150. NSArray * array = [urlStr componentsSeparatedByString:@"=="];
  1151. urlStr = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1152. NSString * titleStr = @"消息通知";
  1153. titleStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"title"]];
  1154. if (urlStr&&self.tabBarController.selectedIndex == 0) {
  1155. [self JsOpenExternalLink:@{@"url":urlStr,@"title":titleStr}];
  1156. }
  1157. }else {
  1158. NSString *url = [NSString stringWithFormat:@"%@%@", kHost, urlStr];
  1159. url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1160. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  1161. }
  1162. }
  1163. - (void)hideTabBar {
  1164. kMainQueue(^{
  1165. if (self.tabBarController.tabBar.hidden == YES) {
  1166. return;
  1167. }
  1168. UIView *contentView;
  1169. if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
  1170. contentView = [self.tabBarController.view.subviews objectAtIndex:1];
  1171. else
  1172. contentView = [self.tabBarController.view.subviews objectAtIndex:0];
  1173. 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);
  1174. self.tabBarController.tabBar.hidden = YES;
  1175. });
  1176. }
  1177. - (void)showTabBar{
  1178. kMainQueue(^{
  1179. if (self.tabBarController.tabBar.hidden == NO)
  1180. {
  1181. return;
  1182. }
  1183. UIView *contentView;
  1184. if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
  1185. contentView = [self.tabBarController.view.subviews objectAtIndex:1];
  1186. else
  1187. contentView = [self.tabBarController.view.subviews objectAtIndex:0];
  1188. 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);
  1189. self.tabBarController.tabBar.hidden = NO;
  1190. });
  1191. }
  1192. - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
  1193. {
  1194. __block NSString *resultString = nil;
  1195. __block BOOL finished = NO;
  1196. [self.webView evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
  1197. if (error == nil) {
  1198. if (result != nil) {
  1199. resultString = [NSString stringWithFormat:@"%@", result];
  1200. }
  1201. } else {
  1202. NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
  1203. }
  1204. finished = YES;
  1205. }];
  1206. while (!finished) {
  1207. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
  1208. }
  1209. return resultString;
  1210. }
  1211. -(void)hiddenMethodTabBar
  1212. {
  1213. kMainQueue(^{
  1214. if (iPhoneX) {
  1215. if (@available(iOS 11.0, *)) {
  1216. self.webView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
  1217. }
  1218. }else {
  1219. self.webView.frame = CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT+STATUS_BAR_HEIGHT);
  1220. }
  1221. });
  1222. }
  1223. -(void)showMethodTabBar
  1224. {
  1225. kMainQueue(^{
  1226. if (iPhoneX) {
  1227. if (@available(iOS 11.0, *)) {
  1228. self.webView.frame = CGRectMake(0, 0, WIDTH, HEIGHT-TAB_BAR_HEIGHT);
  1229. }
  1230. }else {
  1231. self.webView.frame = CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT-TAB_BAR_HEIGHT+STATUS_BAR_HEIGHT);
  1232. }
  1233. });
  1234. }
  1235. //取消获取照片
  1236. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
  1237. {
  1238. dispatch_async(dispatch_get_main_queue(), ^{
  1239. [picker dismissViewControllerAnimated:YES completion:^{
  1240. [self uploadUrl:@""];
  1241. }];
  1242. });
  1243. }
  1244. //上传图片
  1245. -(void)uploadPic:(NSData *)data
  1246. {
  1247. NSDictionary * body = @{@"type":@"courseFile"};
  1248. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  1249. //ContentType设置
  1250. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",@"text/plain",nil];
  1251. manager.responseSerializer= [AFHTTPResponseSerializer serializer];
  1252. manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  1253. manager.requestSerializer.timeoutInterval = 15.0f;
  1254. [manager POST:[NSString stringWithFormat:@"%@filemanage/upload",kHost] parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  1255. //上传的参数(上传图片,以文件流的格式)
  1256. [formData appendPartWithFileData:data
  1257. name:@"courseFile"
  1258. fileName:@"courseFile.jpeg"
  1259. mimeType:@"image/jpeg"];
  1260. } progress:^(NSProgress * _Nonnull uploadProgress) {
  1261. CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
  1262. NSLog(@"%.2lf%%", progress);
  1263. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  1264. //请求成功的block回调
  1265. NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
  1266. NSLog(@"上传成功%@",dic);
  1267. if ([dic[@"msg"] isEqualToString:@"ssss"]) {
  1268. [self uploadUrl:dic[@"url"]];
  1269. }else{
  1270. [self uploadUrl:@""];
  1271. }
  1272. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  1273. NSLog(@"上传失败%@",error);
  1274. [self uploadUrl:@""];
  1275. [[GlobalData shareInstance] addOnePlistData:@{
  1276. @"detail":@"上传图片接口",
  1277. @"reqTime":[NSNumber numberWithInt:0],
  1278. }];
  1279. }];
  1280. }
  1281. -(void)uploadUrl:(NSString *)url {
  1282. NSString *textJS = [NSString new];
  1283. NSString *methodJS = [NSString new];
  1284. if ([url isEqualToString:@""]) {
  1285. textJS = @"hiddenLoading()";
  1286. methodJS =@"hiddenLoading";
  1287. }else{
  1288. textJS = [NSString stringWithFormat:@"uploadImg('%@')",url];
  1289. methodJS = @"uploadImg";
  1290. }
  1291. if ([url isEqualToString:@""]||[textJS isEqualToString:@""]) {
  1292. NSLog(@"空的情况");
  1293. textJS = @"hiddenLoading()";
  1294. methodJS = @"hiddenLoading";
  1295. }
  1296. NSDictionary *dict = @{@"jsStr":textJS,@"name":methodJS};
  1297. [self performSelector:@selector(uploadJS:) withObject:dict afterDelay:1];
  1298. }
  1299. //获取到图片
  1300. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
  1301. {
  1302. dispatch_async(dispatch_get_main_queue(), ^{
  1303. [picker dismissViewControllerAnimated:YES completion:^{
  1304. UIImage * img=[info objectForKey:UIImagePickerControllerEditedImage];
  1305. NSData *data = UIImageJPEGRepresentation(img, 0.5);
  1306. if (data!=nil) {
  1307. [self uploadPic:data];
  1308. }else{
  1309. NSLog(@"data == nil");
  1310. [self uploadUrl:@""];
  1311. }
  1312. }];
  1313. });
  1314. }
  1315. -(void)uploadJS:(NSDictionary *)dict {
  1316. [self isExitCallToJS:dict[@"jsStr"] withMethodName:dict[@"name"]];
  1317. }
  1318. - (BOOL)checkLocationServiceIsEnabled{
  1319. // 该方法是类方法,和我们创建的管理器没有关系
  1320. if ([CLLocationManager locationServicesEnabled]) {
  1321. return YES;
  1322. }
  1323. return NO;
  1324. }
  1325. - (void)createCLManager{
  1326. // 创建CoreLocation管理对象
  1327. self.locaationManager = [[CLLocationManager alloc]init];
  1328. // 设定定位精准度
  1329. [self.locaationManager setDesiredAccuracy:kCLLocationAccuracyBest];
  1330. // 设定DistanceFilter可以在用户移动指定距离之后触发更新事件(100米更新一次)
  1331. [self.locaationManager setDistanceFilter:1.f];
  1332. // 设置代理
  1333. self.locaationManager.delegate = self;
  1334. // 开始更新定位
  1335. [self.locaationManager startUpdatingLocation];
  1336. }
  1337. // 代理方法,更新位置
  1338. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
  1339. CLLocation * newLocation = [locations lastObject];
  1340. // 判空处理
  1341. if (newLocation.horizontalAccuracy < 0) {
  1342. return;
  1343. }
  1344. CLGeocoder *geocoder = [[CLGeocoder alloc] init];
  1345. [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
  1346. for (CLPlacemark *placeMark in placemarks) {
  1347. //NSLog(@"位置:%@", placeMark.name);
  1348. //NSLog(@"街道:%@", placeMark.thoroughfare);
  1349. //NSLog(@"子街道:%@", placeMark.subThoroughfare);
  1350. //NSLog(@"区\\县:%@", placeMark.subLocality);
  1351. //NSLog(@"市:%@", placeMark.locality);
  1352. //NSLog(@"行政区:%@", placeMark.administrativeArea);
  1353. //NSLog(@"国家:%@", placeMark.country);
  1354. self.placeAdr = [placeMark.administrativeArea stringByAppendingString:[NSString stringWithFormat:@"-%@",placeMark.locality]];
  1355. }
  1356. }];
  1357. }
  1358. // 代理方法,定位权限检查
  1359. -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
  1360. switch (status) {
  1361. case kCLAuthorizationStatusNotDetermined:{
  1362. NSLog(@"用户还未决定授权");
  1363. // 主动获得授权
  1364. [self.locaationManager requestWhenInUseAuthorization];
  1365. break;
  1366. }
  1367. case kCLAuthorizationStatusRestricted:
  1368. {
  1369. NSLog(@"访问受限");
  1370. // 主动获得授权
  1371. [self.locaationManager requestWhenInUseAuthorization];
  1372. break;
  1373. }
  1374. case kCLAuthorizationStatusDenied:{
  1375. // 此时使用主动获取方法也不能申请定位权限
  1376. // 类方法,判断是否开启定位服务
  1377. if ([CLLocationManager locationServicesEnabled]) {
  1378. NSLog(@"定位服务开启,被拒绝");
  1379. } else {
  1380. NSLog(@"定位服务关闭,不可用");
  1381. }
  1382. break;
  1383. }
  1384. case kCLAuthorizationStatusAuthorizedAlways:{
  1385. NSLog(@"获得前后台授权");
  1386. break;
  1387. }
  1388. case kCLAuthorizationStatusAuthorizedWhenInUse:{
  1389. NSLog(@"获得前台授权");
  1390. break;
  1391. }
  1392. default:
  1393. break;
  1394. }
  1395. }
  1396. -(NSString *)convertToJsonData:(NSDictionary *)dict {
  1397. NSError *error;
  1398. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
  1399. NSString *jsonString;
  1400. if (!jsonData) {
  1401. NSLog(@"%@",error);
  1402. }else{
  1403. jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
  1404. }
  1405. NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
  1406. NSRange range = {0,jsonString.length};
  1407. //去掉字符串中的空格
  1408. [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
  1409. NSRange range2 = {0,mutStr.length};
  1410. //去掉字符串中的换行符
  1411. [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
  1412. return mutStr;
  1413. }
  1414. -(void)addNoNetViews{
  1415. kMainQueue(^{
  1416. [self removeNoNetViews];
  1417. self.noNetView = [NoNetView shareView];
  1418. [self.view addSubview:self.noNetView];
  1419. });
  1420. }
  1421. -(void)removeNoNetViews{
  1422. if (self.noNetView ) {
  1423. [self.noNetView removeFromSuperview];
  1424. self.noNetView = nil;
  1425. }
  1426. }
  1427. #pragma mark **** 通知相关方法
  1428. // 点击通知 跳转到通知内url
  1429. -(void)requestWebView:(NSNotification *)notification{
  1430. NSDictionary * infoDict = [notification object];
  1431. if (!infoDict) {
  1432. return;
  1433. }
  1434. NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"url"]];
  1435. if (urlStr) {
  1436. //当前控制器
  1437. if(self.tabBarController.selectedIndex != 0) {
  1438. return;
  1439. }
  1440. [self performSelector:@selector(requestWebTime:) withObject:infoDict afterDelay:1];
  1441. }
  1442. }
  1443. -(void)clickSubNotiMethods:(NSNotification *)notification{
  1444. NSDictionary * infoDict = [notification object][@"info"];
  1445. if (!infoDict) {
  1446. return;
  1447. }
  1448. NSLog(@"%@",infoDict);
  1449. NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"url"]];
  1450. if (urlStr) {
  1451. NSLog(@"有info");
  1452. if(self.tabBarController.selectedIndex == 0) {
  1453. //底部栏置换到订阅
  1454. AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1455. JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
  1456. tab.selectedIndex = 1;
  1457. [self performSelector:@selector(pushDY:) withObject:infoDict afterDelay:1];
  1458. }
  1459. }
  1460. }
  1461. //点击支付通知
  1462. -(void)clickPayMethods:(NSNotification *)notification{
  1463. NSDictionary * infoDict = [notification object][@"info"];
  1464. if (!infoDict) {
  1465. return;
  1466. }
  1467. NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"url"]];
  1468. NSArray * array = [urlStr componentsSeparatedByString:@"=="];
  1469. urlStr = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1470. NSString * titleStr = @"消息通知";
  1471. titleStr = [NSString stringWithFormat:@"%@",infoDict[@"title"]];
  1472. if (urlStr) {
  1473. if(self.tabBarController.selectedIndex == 0) {
  1474. [self JsOpenExternalLink:@{@"url":urlStr,@"title":titleStr}];
  1475. }
  1476. }
  1477. }
  1478. -(void)alipayWXpayStatus:(NSNotification *)notification{
  1479. NSString * status = [notification object];
  1480. [self performSelector:@selector(payStatus:) withObject:status afterDelay:2];
  1481. }
  1482. -(void)payStatus:(NSString *)status
  1483. {
  1484. //目前延时两秒
  1485. NSLog(@"支付状态:%@",status);
  1486. if(self.tabBarController.selectedIndex == 0) {
  1487. [self isExitCallToJS:[NSString stringWithFormat:@"payCallBack('%@')", status] withMethodName:@"payCallBack"];
  1488. }
  1489. }
  1490. // 调用js方法 刷新推送权限状态
  1491. -(void)updateNotifyState{
  1492. if (self.updateNotify) {
  1493. self.updateNotify = NO;
  1494. [self isExitCallToJS:[NSString stringWithFormat:@"updateNoticeSwitch()"] withMethodName:@"updateNoticeSwitch"];
  1495. }
  1496. }
  1497. // 收到通知消息
  1498. -(void)afterReceiveNewMsg{
  1499. NSLog(@"afterReceiveNewMsg");
  1500. [self isExitCallToJS:@"afterReceiveNewMsg()" withMethodName:@"afterReceiveNewMsg"];
  1501. }
  1502. // 再次加载页面
  1503. -(void)reloadWebView{
  1504. if(self.tabBarController.selectedIndex == 0) {
  1505. if (!self.webView.canGoBack) {
  1506. [self webViewFirstRequest];
  1507. }else{
  1508. [self.webView reload];
  1509. }
  1510. }
  1511. }
  1512. // 收到退出登录消息
  1513. -(void)loginOut:(NSNotification *)notification{
  1514. if([notification.userInfo[@"item_index"] integerValue]!=0) {
  1515. return;
  1516. }
  1517. [self webViewRequestByMsg];
  1518. }
  1519. //收到消息退出并重新加载web
  1520. -(void)webViewRequestByMsg{
  1521. NSString *url = [NSString stringWithFormat:@"%@%@", kHost, @"jyapp/free/login?back=index&isios=t&flag=kicked"];
  1522. url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1523. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  1524. }
  1525. // 监控网络状态变化
  1526. -(void)netReachChanged:(NSNotification *)notificaition{
  1527. NSDictionary *userInfo = notificaition.userInfo;
  1528. if ([userInfo[@"AFNetworkingReachabilityNotificationStatusItem"] intValue] == 0 || [userInfo[@"AFNetworkingReachabilityNotificationStatusItem"] intValue] == -1) {
  1529. [self addNoNetViews];
  1530. }else{
  1531. [self removeNoNetViews];
  1532. }
  1533. }
  1534. //前往登录页面
  1535. -(void)isLoginTabBar:(NSNotification *)notification
  1536. {
  1537. NSDictionary *dict = notification.userInfo;
  1538. NSLog(@"我从第几个页面过来:%@",dict[@"item_index"]);
  1539. pushIndex = [dict[@"item_index"] integerValue];
  1540. NSString *url = [NSString stringWithFormat:@"%@%@", kHost, @"jyapp/free/login"];
  1541. url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  1542. [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
  1543. }
  1544. -(void)newsRedPoint:(NSNotification *)notificaition
  1545. {
  1546. NSDictionary *dict = notificaition.userInfo;
  1547. NSLog(@"%@",dict);
  1548. NSInteger type = [dict[@"type"] integerValue];
  1549. if(type==1) {
  1550. //显示
  1551. kMainQueue(^{
  1552. [self.tabBarController.tabBar showBadgeOnItemIndex:1];
  1553. });
  1554. }else if (type==2) {
  1555. //显示
  1556. kMainQueue(^{
  1557. [self.tabBarController.tabBar showBadgeOnItemIndex:3];
  1558. });
  1559. }else {
  1560. }
  1561. if(self.tabBarController.selectedIndex == 0) {
  1562. NSString *textJS = [NSString stringWithFormat:@"afterReceivePushMessage('%@','%@')",dict[@"typeMsg"],dict[@"url"]];
  1563. [self isExitCallToJS:textJS withMethodName:@"afterReceivePushMessage"];
  1564. }
  1565. }
  1566. //刷新页面相关
  1567. -(void)refreshNonCurVC:(NSNotification *)notificaition{
  1568. if(self.tabBarController.selectedIndex != 0) {
  1569. [self webViewFirstRequest];
  1570. }
  1571. }
  1572. -(void)refreshAllVC:(NSNotification *)notificaition{
  1573. [self webViewFirstRequest];
  1574. }
  1575. -(void)clearWeb{
  1576. NSURLCache * cache = [NSURLCache sharedURLCache];
  1577. [cache removeAllCachedResponses];
  1578. [cache setDiskCapacity:0];
  1579. [cache setMemoryCapacity:0];
  1580. }
  1581. - (void)clearCache {
  1582. /* 取得Library文件夹的位置*/
  1583. NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)[0];
  1584. /* 取得bundle id,用作文件拼接用*/
  1585. NSString *bundleId = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleIdentifier"];
  1586. /*
  1587. * 拼接缓存地址,具体目录为App/Library/Caches/你的APPBundleID/fsCachedData
  1588. */
  1589. NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
  1590. NSError *error;
  1591. /* 取得目录下所有的文件,取得文件数组*/
  1592. NSFileManager *fileManager = [NSFileManager defaultManager];
  1593. // NSArray *fileList = [[NSArray alloc] init];
  1594. //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
  1595. NSArray *fileList = [fileManager contentsOfDirectoryAtPath:webKitFolderInCachesfs error:&error];
  1596. /* 遍历文件组成的数组*/
  1597. for(NSString * fileName in fileList){
  1598. /* 定位每个文件的位置*/
  1599. NSString * path = [[NSBundle bundleWithPath:webKitFolderInCachesfs] pathForResource:fileName ofType:@""];
  1600. /* 将文件转换为NSData类型的数据*/
  1601. NSData * fileData = [NSData dataWithContentsOfFile:path];
  1602. /* 如果FileData的长度大于2,说明FileData不为空*/
  1603. if(fileData.length >2){
  1604. /* 创建两个用于显示文件类型的变量*/
  1605. int char1 =0;
  1606. int char2 =0;
  1607. [fileData getBytes:&char1 range:NSMakeRange(0,1)];
  1608. [fileData getBytes:&char2 range:NSMakeRange(1,1)];
  1609. /* 拼接两个变量*/
  1610. NSString *numStr = [NSString stringWithFormat:@"%i%i",char1,char2];
  1611. /* 如果该文件前四个字符是6033,说明是Html文件,删除掉本地的缓存*/
  1612. if([numStr isEqualToString:@"6033"]){
  1613. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@",webKitFolderInCachesfs,fileName]error:&error];
  1614. continue;
  1615. }
  1616. }
  1617. }
  1618. }
  1619. /*
  1620. #pragma mark - Navigation
  1621. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1622. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1623. // Get the new view controller using [segue destinationViewController].
  1624. // Pass the selected object to the new view controller.
  1625. }
  1626. */
  1627. @end