12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523 |
- //
- // JYNewSearchViewController.m
- // JianYuIOS
- //
- // Created by apple on 2020/6/5.
- // Copyright © 2020 lixianglan. All rights reserved.
- //
- #import "JYNewSearchViewController.h"
- #import <WebKit/WebKit.h>
- #import "JYTabBarController.h"
- #import <CoreLocation/CoreLocation.h>
- @interface JYNewSearchViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,CLLocationManagerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
- {
- NSInteger _timeTick;
- NSInteger _time;
- NSInteger pushIndex;//第几个模块过来的
- BOOL notiFinish;
- BOOL refreshTabBool; //实验室-百宝箱 是否刷新
- BOOL isLoadRedDot;
- CGPoint startTouch;
- BOOL _isMoving;
- }
- @property (nonatomic, strong) UIProgressView *progressView;
- @property (nonatomic, strong) WKWebView *webView;
- @property (nonatomic, strong)NSMutableDictionary *notiDict;
- @property (nonatomic,weak)NSTimer *timer;
- @property(nonatomic, assign)BOOL updateNotify;
- @property(nonatomic, assign)BOOL afterOpenPushMessage;
- @property(nonatomic,strong)CLLocationManager *locaationManager;
- @property(nonatomic,strong)NSString *placeAdr;
- @property(nonatomic,assign)BOOL isLocation;
- @property(nonatomic, strong)NoNetView *noNetView;
- @end
- NSString *const new_kInitVector_1 = @"1389461544135476";
- size_t const new_kKeySize_1 = kCCKeySizeAES128;
- NSString *const new_AesKey_1 = @"mGlAgnIBB8bx2nch";
- @implementation JYNewSearchViewController
- -(void)viewWillAppear:(BOOL)animated
- {
- [super viewWillAppear:animated];
- [self.navigationController setNavigationBarHidden:YES animated:animated];
- }
- //进度条
- - (UIProgressView *)progressView
- {
- if (_progressView == nil) {
- _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,STATUS_BAR_HEIGHT - 2,WIDTH,2)];
- _progressView.tintColor = [UIColor blueColor];
- _progressView.trackTintColor = [UIColor whiteColor];
- }
- return _progressView;
- }
- //懒加载
- - (WKWebView *)webView
- {
- if(_webView == nil) {
- WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
- config.preferences = [[WKPreferences alloc] init];
- config.preferences.minimumFontSize = 0;
- config.preferences.javaScriptEnabled = YES;
- config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
- //添加消息处理,注意:self指代的是需要遵守WKScriptMessageHandler协议,结束时需要移除
- config.userContentController = [[WKUserContentController alloc] init];
- //声明协议
- NSArray *jsArr = @[@"loginByWeixin",
- @"share",
- @"saveUserToken",
- @"removeUserToken",
- @"openSystemNotification",
- @"openExternalLink",
- @"alert",
- @"hiddenBottom",
- @"checkLab",
- @"loginSuccess",
- @"backUrl",
- @"clearPushMessage",
- @"hideRedSpotOnMenu",
- @"showRedSpotOnMenu",
- @"wxPay",
- @"aliPay",
- @"chooseTab",
- @"skipCamera",
- @"skipAlbum",
- @"appTest",
- ];
- for (NSString*jsName in jsArr) {
- [config.userContentController addScriptMessageHandler:self name:jsName];
- }
- //高端的自定义配置创建WKWebView
- if (iPhoneX) {
- _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-TAB_BAR_HEIGHT) configuration:config];
- if (@available(iOS 11.0, *)) {
- _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
- }
- }else {
- _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT-TAB_BAR_HEIGHT+STATUS_BAR_HEIGHT) configuration:config];
- }
- _webView.scrollView.bounces = NO;
- _webView.UIDelegate = self;
- _webView.navigationDelegate = self;
- // _webView.allowsBackForwardNavigationGestures = true;
- [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
- }
- return _webView;
- }
- -(void)webViewFirstRequest
- {
- NSString *url = [NSString stringWithFormat:@"%@%@", kHost, @"jyapp/free/index"];
- NSString *token = [LXUserDefaults token];
- if (token) {
- url = [url stringByAppendingString:[NSString stringWithFormat:@"?sign=%@&url=/jyapp/jylab/mainSearch&from=restart", token]];
- }
- NSLog(@"111 :第一次加载:%@",url);
- url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- kMainQueue(^{
- [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
- })
- }
- #pragma mark - event response
- // 计算wkWebView进度条
- - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
- if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
- CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
- self.progressView.alpha = 1.0f;
- [self.progressView setProgress:newprogress animated:YES];
- if (newprogress >= 1.0f) {
- [UIView animateWithDuration:0.3f
- delay:0.3f
- options:UIViewAnimationOptionCurveEaseOut
- animations:^{
- self.progressView.alpha = 0.0f;
- }
- completion:^(BOOL finished) {
- [self.progressView setProgress:0 animated:NO];
- }];
- }
-
- } else {
- [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
- }
- }
- -(void)initNotification {
- //加载通知
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestWebView:) name:kRequestWebViewWithUrl object:nil];
- //点击订阅通知
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickSubNotiMethods:) name:ClickSubNotiMethods object:nil];
- //点击支付通知
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickPayMethods:) name:ClickPayMethods object:nil];
- //支付状态通知
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayWXpayStatus:) name:AlipayWXpayStatus object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotifyState) name:kUpdateNotifyState object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(afterReceiveNewMsg) name:kAfterReceiveNewMsg object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadWebView) name:kReloadWebVIew object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOut:) name:kLoginOut object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netReachChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
- //展示底部红的通知
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsRedPoint:) name:JYNewsRedPoint object:nil];
- //接收全新通知
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshNonCurVC:) name:RefreshNonCurVC object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAllVC:) name:RefreshAllVC object:nil];
- }
- #pragma mark – Gesture Recognizer –
- -(void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
- {
- NSString *current_url = [self stringByEvaluatingJavaScriptFromString:@"document.location.href"];
- NSLog(@"当前页面:%@",current_url);
- CGRect rect = self.view.bounds;
- CGFloat width = CGRectGetWidth(rect);
- if (![self.webView canGoBack]) {
- NSLog(@"不可返回");
- return;
- }
- if([current_url containsString:@"jyapp/free/login"]) {
- return;
- }
-
- // NSString *current_url = self.webView.request.URL.absoluteString;
- 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]]){
- return;
- }
-
- //https://www.jianyu360.com/jyapp/free/me
- //https://www.jianyu360.com/jyapp/jylab/index
- //https://www.jianyu360.com/jyapp/wxkeyset/keyset/index
- //https://www.jianyu360.com/jyapp/jylab/mainSearch
-
- CGPoint touchPoint = [recoginzer locationInView:[UIApplication sharedApplication].keyWindow];
- if (recoginzer.state==UIGestureRecognizerStateBegan) {
- _isMoving = YES;
- startTouch = touchPoint;
- } else if (recoginzer.state==UIGestureRecognizerStateEnded){
- if (touchPoint.x - startTouch.x > width*0.125) {
- [UIView animateWithDuration:0.3 animations:^{
- [self moveViewWithX:width];
- [self.webView goBack];
- [self isExitCallToJS:@"afterClickBack()" withMethodName:@"afterClickBack"];
- } completion:^(BOOL finished) {
- _isMoving = NO;
- [self moveViewWithX:0];
- }];
- } else {
- [UIView animateWithDuration:0.3 animations:^{
- [self moveViewWithX:0];
- } completion:^(BOOL finished) {
- _isMoving = NO;
- }];
- }
- return;
- } else if (recoginzer.state==UIGestureRecognizerStateCancelled){
- [UIView animateWithDuration:0.3 animations:^{
- [self moveViewWithX:0];
- } completion:^(BOOL finished) {
- _isMoving = NO;
- }];
- return;
- }
- if (_isMoving) {
- [self moveViewWithX:touchPoint.x - startTouch.x];
- }
- }
- -(void)moveViewWithX:(float)x
- {
- CGRect rect = self.view.bounds;
- CGFloat width = CGRectGetWidth(rect);
- x = x>width?width:x;
- x = x<0?0:x;
- CGRect frame = self.webView.frame;
- frame.origin.x = x;
- self.webView.frame = frame;
- }
- - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
- // message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
- NSLog(@"原生收到了js发送过来的消息message.name = %@ message.body = %@",message.name,message.body);
- if ([message.name isEqualToString:@"loginByWeixin"]) {
- [self jsLoginByWeixin:message.body];
- }else if ([message.name isEqualToString:@"share"]) {
- [self jsShare:message.body];
- }else if ([message.name isEqualToString:@"saveUserToken"]) {
- [self jsSaveUserToken:message.body];
- }else if ([message.name isEqualToString:@"removeUserToken"]) {
- [self jsRemoveUserToken:message.body];
- }else if ([message.name isEqualToString:@"openSystemNotification"]) {
- [self jsOpenSystemNotification:message.body];
- }else if ([message.name isEqualToString:@"openExternalLink"]) {
- [self JsOpenExternalLink:message.body];
- }else if ([message.name isEqualToString:@"alert"]) {
- [self jsAlert:message.body];
- }else if ([message.name isEqualToString:@"hiddenBottom"]) {
- [self jsHiddenBottom:message.body];
- }else if ([message.name isEqualToString:@"checkLab"]) {
- [self jsCheckLab:message.body];
- }else if ([message.name isEqualToString:@"loginSuccess"]) {
- [self jsLoginSuccess:message.body];
- }else if ([message.name isEqualToString:@"backUrl"]) {
- [self jsBackUrl:message.body];
- }else if ([message.name isEqualToString:@"clearPushMessage"]) {
- [self jsClearPushMessage:message.body];
- }else if ([message.name isEqualToString:@"hideRedSpotOnMenu"]) {
- [self jsHideRedSpotOnMenu:message.body];
- }else if ([message.name isEqualToString:@"showRedSpotOnMenu"]) {
- [self jsShowRedSpotOnMenu:message.body];
- }else if ([message.name isEqualToString:@"wxPay"]) {
- [self jsWxPay:message.body];
- }else if ([message.name isEqualToString:@"aliPay"]) {
- [self jsAliPay:message.body];
- }else if ([message.name isEqualToString:@"chooseTab"]) {
- [self jsChooseTab:message.body];
- }else if ([message.name isEqualToString:@"skipCamera"]) {
- [self jsSkipCamera:message.body];
- }else if ([message.name isEqualToString:@"skipAlbum"]) {
- [self jsSkipAlbum:message.body];
- }else {
-
- }
- }
- #pragma mark - WKUIDelegate
- - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
- {
- NSError *err = nil;
- NSData *dataFromString = [prompt dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *paramdict = [NSJSONSerialization JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:&err];
- NSLog(@"拦截prompt:%@",paramdict);
- if (!err){
- NSString *type = [paramdict objectForKey:@"jsName"];
- if (type && [type isEqualToString:@"getUserToken"]) {
- NSDictionary *dict = @{@"type":@"string",
- @"value":[self jsGetUserToken:paramdict]};
- completionHandler([self convertToJsonData:dict]);
- }else if (type && [type isEqualToString:@"getVersion"]) {
- NSDictionary *dict = @{@"type":@"string",
- @"value":[self jsGetVersion:paramdict]};
- completionHandler([self convertToJsonData:dict]);
- }else if (type && [type isEqualToString:@"checkNoticePermission"]) {
- NSDictionary *dict = @{@"type":@"int",
- @"value":[NSString stringWithFormat:@"%d",[self jsCheckNoticePermission:paramdict]]};
- completionHandler([self convertToJsonData:dict]);
- }else if (type && [type isEqualToString:@"getPushRid"]) {
- NSDictionary *dict = @{@"type":@"string",@"value":[self jsGetPushRid:paramdict]};
- completionHandler([self convertToJsonData:dict]);
- }else if (type && [type isEqualToString:@"isInstallWeixin"]) {
- NSDictionary *dict = @{@"type":@"int",
- @"value":[NSString stringWithFormat:@"%d",[self jsIsInstallWeixin:paramdict]]};
- completionHandler([self convertToJsonData:dict]);
- }else if (type && [type isEqualToString:@"getCipherText"]) {
- NSDictionary *dict = @{@"type":@"string",
- @"value":[self jsGetCipherText:paramdict]};
- completionHandler([self convertToJsonData:dict]);
- }
- else if (type && [type isEqualToString:@"getOtherPushRid"]) {
- NSDictionary *dict = @{@"type":@"string",@"value":[self jsGetOtherPushRid:paramdict]};
- completionHandler([self convertToJsonData:dict]);
- }else if (type && [type isEqualToString:@"getPhoneBrand"]) {
- NSDictionary *dict = @{@"type":@"string",
- @"value":[self jsGetPhoneBrand:paramdict]};
- completionHandler([self convertToJsonData:dict]);
- }else if (type && [type isEqualToString:@"getLocation"]) {
- NSDictionary *dict = @{@"type":@"string",
- @"value":[self jsGetLocation:paramdict]};
- completionHandler([self convertToJsonData:dict]);
- }else {
- completionHandler(@"");
- }
-
-
- }
- }
- - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
- // 获取完整url并进行UTF-8转码
- NSString *strRequest = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
- if ([strRequest containsString:@"jyapp/article/content"]) {
- NSLog(@"拦截的链接:%@",strRequest);
- if (![strRequest containsString:kHost]) {
- NewWebController *ctr = [[NewWebController alloc] init];
- ctr.url = strRequest;
- ctr.titleShow = [self stringByEvaluatingJavaScriptFromString:@"document.title"];
- kMainQueue(^{
- [self presentViewController:ctr animated:NO completion:nil];
- });
- // 不允许跳转
- decisionHandler(WKNavigationActionPolicyCancel);
- }
-
- }
- // 允许跳转
- decisionHandler(WKNavigationActionPolicyAllow);
-
-
- }
- //通过js alert 显示一个警告面板,调用原生会走此方法。
- - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
- {
- NSLog(@"显示一个JavaScript警告面板, message = %@",message);
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
- [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
- completionHandler();
- }]];
- [self presentViewController:alertController animated:YES completion:nil];
- }
- //通过 js confirm 显示一个确认面板,调用原生会走此方法。
- - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
- {
- NSLog(@"运行JavaScript确认面板, message = %@", message);
- UIAlertController *action = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
- [action addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
- completionHandler(NO);
- }] ];
- [action addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
- completionHandler(YES);
- }]];
- [self presentViewController:action animated:YES completion:nil];
- }
- #pragma mark - OC调JS交互
- -(void)isExitCallToJS:(NSString *)jsStr withMethodName:(NSString *)name{
- NSString *jsName = [NSString stringWithFormat:@"function exist(){return !window['%@']};exist()",name];
- [_webView evaluateJavaScript:jsName completionHandler:^(id _Nullable result, NSError * _Nullable error) {
- NSLog(@"是否存在 result:%@,error:%@",result,error);
- if ([result intValue]==0) {
- [self executeCallJS:jsStr];
- }else {
- NSLog(@"不存在-不存在-不存在-%@",jsStr);
- }
- }];
- }
- -(void)executeCallJS:(NSString *)jsStr {
-
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- NSLog(@"OC调JS交互%@:",jsStr);
- [_webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
- if (error!=nil) {
- NSLog(@"result:%@,error:%@",result,error);
- [[LXViewControllerManager shareViewControllerManager]showAlertViewWithMessage: jsStr];
- }
- }];
- });
-
-
-
- }
- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- NSLog(@"首页初始化");
- self.view.backgroundColor = [UIColor whiteColor];
- [self.view addSubview:self.webView];
- [self.view addSubview:self.progressView];
- [self webViewFirstRequest];
- [[AFNetworkReachabilityManager sharedManager] startMonitoring];
- [self initApnsTimer];
- [self initNotification];
-
- UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(paningGestureReceive:)];
- [recognizer delaysTouchesBegan];
- [self.view addGestureRecognizer:recognizer];
-
- //初始化临时属性
- self.placeAdr = [NSString new];
- }
- -(void)initApnsTimer {
- //定时器
- if([LXUserDefaults token]) {
- self.notiDict = [[NSMutableDictionary alloc]initWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"NotiDict"]];
- if(self.notiDict.count) {
- self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
- }
- }
- }
- -(void)haveRedPoint
- {
- NSLog(@"http请求-------小红点");
- NSString *token = [LXUserDefaults token];
- if (token) {
- [[LXNetworkManager shareLXNetworkManager]postWithURLStr:[NSString stringWithFormat:@"%@jyapp/free/showRedSpotOnMenu",kHost] parameters:@{@"token":token} progress:^(NSProgress *progress) {
- NSLog(@"%@",progress);
- } success:^(id responseObject) {
- NSLog(@"responseObject=%@",responseObject);
-
- if([responseObject[@"subscribe"] integerValue]>=1) {
- //显示
- [GlobalData shareInstance].subIsRed = YES;
- kMainQueue(^{
- [self.tabBarController.tabBar showBadgeOnItemIndex:1];
- });
- }else {
- [GlobalData shareInstance].subIsRed = NO;
- kMainQueue(^{
- [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
- });
- }
-
- if([responseObject[@"my"] integerValue]>=1) {
- //显示
- [GlobalData shareInstance].mineIsRed = YES;
- kMainQueue(^{
- [self.tabBarController.tabBar showBadgeOnItemIndex:3];
- });
- }else {
- [GlobalData shareInstance].mineIsRed = NO;
- kMainQueue(^{
- [self.tabBarController.tabBar hideBadgeOnItemIndex:3];
- });
- }
-
- } failure:^(NSError *error) {
- NSLog(@"error=%@",error);
- }];
- }
- }
- #pragma mark - WKNavigationDelegate
- /* 页面加载完成 */
- - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
- NSLog(@"-----页面加载完成%@",[self stringByEvaluatingJavaScriptFromString:@"document.location.href"]);
- //第一次加载小红点
- if(!isLoadRedDot) {
- isLoadRedDot = true;
- [self haveRedPoint];
- }
- if(!notiFinish) {
- notiFinish = YES;
- }
-
- if(refreshTabBool){
- NSLog(@"刷新-刷新-刷新-刷新-")
- refreshTabBool = NO;
- }else {
- //正常的网页加载
- [self judgeIsHidden];//是否隐藏
- }
-
- [self removeNoNetViews];
- [[LXViewControllerManager shareViewControllerManager] hideHud];
-
- [self isExitCallToJS:@"afterPageInit()" withMethodName:@"afterPageInit"];
- if (self.afterOpenPushMessage) {
- self.afterOpenPushMessage = NO;
- [self isExitCallToJS:[NSString stringWithFormat:@"afterOpenPushMessage('%d')", [self jsIsCanBack:nil]] withMethodName:@"afterOpenPushMessage"];
- }
-
-
-
-
- }
- /* 页面开始加载 */
- - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
- }
- /* 开始返回内容 */
- - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
- }
- /* 页面加载失败 */
- - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
- [[LXViewControllerManager shareViewControllerManager] hideHud];
- }
- #pragma mark *****JS与OC交互
- #pragma mark - WKScriptMessageHandler JS调OC交互
- -(void)jsLoginByWeixin:(NSDictionary *)dict {
- if ([LXUserDefaults isInstallWeiXin] != 1) { // 没有安装微信 不走友盟
- [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"微信登录失败,没有安装微信" delay:1.5];
- return;
- }
- [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error) {
- UMSocialUserInfoResponse *resp = result;
- [self dealWXDic:(NSDictionary *)resp.originalResponse];
- [[LXViewControllerManager shareViewControllerManager] hideHud];
- }];
- }
- // 处理微信登录获取到的数据
- -(void)dealWXDic:(NSDictionary *)dictionary{
- [[LXViewControllerManager shareViewControllerManager] showHudText:nil];
- //如果获取到用户信息,即用户点击了“登录”,则进行用户信息获取
- if (dictionary.count > 0) {
- NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:dictionary];
- if (dic) {
- [dic removeObjectForKey:@"privilege"];
- [dic removeObjectForKey:@"language"];
- double currDouble = [[NSDate date] timeIntervalSince1970];
- [dic setObject:[NSNumber numberWithLong:(long)currDouble] forKey:@"createtime"];
- // 拼接标志位
- 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"]];
- sign = [LXMD5 md532BitLower:sign];
- [dic setObject:sign forKey:@"sign"];
- NSString *endStr = [[LXViewControllerManager shareViewControllerManager] getJsonStr:dic];
- NSData *data = [endStr dataUsingEncoding:NSUTF8StringEncoding];
- endStr = [data base64EncodedStringWithOptions:0];
- [self isExitCallToJS:[NSString stringWithFormat:@"loginByWeixinCallBack('%@')", endStr] withMethodName:@"loginByWeixinCallBack"];
- }
- }
- }
- -(void)jsShare:(NSDictionary *)dict {
- NSString *type = [NSString stringWithFormat:@"%@",dict[@"type"]];
- NSString *title = [NSString stringWithFormat:@"%@",dict[@"title"]];
- NSString *content = [NSString stringWithFormat:@"%@",dict[@"content"]];
- NSString *link = [NSString stringWithFormat:@"%@",dict[@"link"]];
- UMSocialPlatformType shareType;
- if ([type intValue] == 1) { // 微信好友
- shareType = UMSocialPlatformType_WechatSession;
- }else if ([type intValue] == 2){ /// qq好友
- shareType = UMSocialPlatformType_QQ;
- }else if ([type intValue] == 3){ // 朋友圈
- shareType = UMSocialPlatformType_WechatTimeLine;
- }else{
- shareType = UMSocialPlatformType_WechatSession;
- }
- if ([type intValue] == 1 || [type intValue] == 3) {
- if ([LXUserDefaults isInstallWeiXin] != 1) {
- [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"没有安装微信" delay:1.5];
- return;
- }
- }
- if ([type intValue] == 2) {
- if (![[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_QQ]) {
- [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"没有安装QQ" delay:1.5];
- return;
- }
- }
- //创建分享消息对象
- UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
- //创建网页内容对象
- UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:content thumImage:[UIImage imageNamed:@"logo"]];
- //设置网页地址
- shareObject.webpageUrl = link;
- messageObject.shareObject = shareObject;
- //调用分享接口
- [[UMSocialManager defaultManager] shareToPlatform:shareType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
- if (error) {
- if (error.userInfo[@"message"] && [error.userInfo[@"message"] containsString:@"Operation is cancel"]) {
- [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"取消分享" delay:1];
- }else{
- [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:error.userInfo[@"message"] delay:1];
- }
- [self isExitCallToJS:[NSString stringWithFormat:@"shareCallBack('%@','%@')",type,@"0"] withMethodName:@"shareCallBack"];
- }else{
- if ([data isKindOfClass:[UMSocialShareResponse class]]) {
- [self isExitCallToJS:[NSString stringWithFormat:@"shareCallBack('%@','%@')",type,@"1"] withMethodName:@"shareCallBack"];
- }else{
- UMSocialLogInfo(@"response data is %@",data);
- }
- }
- }];
- }
- -(void)jsSaveUserToken:(NSDictionary *)dict{
- [[LXViewControllerManager shareViewControllerManager] hideHud];
- [LXUserDefaults saveToken:[NSString stringWithFormat:@"%@",dict[@"token"]]];
- }
- -(NSString *)jsGetUserToken:(NSDictionary *)dict{
- return [LXUserDefaults token];
- }
- -(void)jsRemoveUserToken:(NSDictionary *)dict{
- [LXUserDefaults clearAll];
- }
- -(int)jsCheckNoticePermission:(NSDictionary *)dict{
- return [LXUserDefaults notifyState];
- }
- // 跳转到系统设置
- -(void)jsOpenSystemNotification:(NSDictionary *)dict{
- self.updateNotify = YES;
- [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
- }
- // 获取推送id
- -(NSString *)jsGetPushRid:(NSDictionary *)dict{
- return [LXUserDefaults registrationID];
- }
- // 打开新页面 加载新web
- -(void)JsOpenExternalLink:(NSDictionary *)dict{
- NSString *url = [NSString stringWithFormat:@"%@",dict[@"url"]];
- NSString *title = [NSString stringWithFormat:@"%@",dict[@"title"]];
- if (url) {
- if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable || [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusUnknown) {
- }
- NewWebController *ctr = [[NewWebController alloc] init];
- ctr.url = url;
- if (!title || [title isEqualToString:@""] || [title isEqualToString:@"undefined"]) {
- ctr.titleShow = nil;
- }else{
- ctr.titleShow = title;
- }
- kMainQueue(^{
- [self presentViewController:ctr animated:NO completion:nil];
- });
- }
- }
- // 获取当前版本号
- -(NSString *)jsGetVersion:(NSDictionary *)dict{
- return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
- }
- -(void)jsAlert:(NSDictionary *)dict{
- [[LXViewControllerManager shareViewControllerManager] showAlertViewWithMessage:[NSString stringWithFormat:@"%@",dict[@"content"]]];
- }
- -(int)jsIsInstallWeixin:(NSDictionary *)dict{
- return [LXUserDefaults isInstallWeiXin];
- }
- -(NSString *)jsGetCipherText:(NSDictionary *)dict{
- NSString *phone = [NSString stringWithFormat:@"%@",dict[@"phone"]];
- NSDate *date=[NSDate date];
- NSDateFormatter *format1=[[NSDateFormatter alloc] init];
- [format1 setDateFormat:@"yyyyMMddhhmmss"];
- NSString *dateStr;
- dateStr=[format1 stringFromDate:date];
- NSLog(@"%@",dateStr);
-
- NSString *content = [[NSString stringWithFormat:@"%@_%@",phone,dateStr] stringByAppendingString:[NSString stringWithFormat:@"_%@",[LXMD5 md532BitLower:[NSString stringWithFormat:@"%@&%@",phone,dateStr]]]];
- NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
- NSUInteger dataLength = contentData.length;
- // 为结束符'\\0' +1
- char keyPtr[new_kKeySize_1 + 1];
- memset(keyPtr, 0, sizeof(keyPtr));
- [new_AesKey_1 getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
- // 密文长度 <= 明文长度 + BlockSize
- size_t encryptSize = dataLength + kCCBlockSizeAES128;
- void *encryptedBytes = malloc(encryptSize);
- size_t actualOutSize = 0;
- NSData *initVector = [new_kInitVector_1 dataUsingEncoding:NSUTF8StringEncoding];
- CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
- kCCAlgorithmAES,
- kCCOptionPKCS7Padding, // 系统默认使用 CBC,然后指明使用 PKCS7Padding
- keyPtr,
- new_kKeySize_1,
- initVector.bytes,
- contentData.bytes,
- dataLength,
- encryptedBytes,
- encryptSize,
- &actualOutSize);
- if (cryptStatus == kCCSuccess) {
- // 对加密后的数据进行 base64 编码
- return [[NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
- }
- free(encryptedBytes);
- return nil;
- }
- -(void)jsHiddenBottom:(NSDictionary *)dict{
- if(self.tabBarController.selectedIndex == 0) {
- if([[NSString stringWithFormat:@"%@",dict[@"hidden"]] integerValue]==0) {
- [self hideTabBar];
- [self hiddenMethodTabBar];
- }else {
- [self showTabBar];
- [self showMethodTabBar];
- }
- }
- }
- -(void)jsCheckLab:(NSDictionary *)dict {
- [[NSNotificationCenter defaultCenter] postNotificationName:RefreshNonCurVC object:nil userInfo:nil];
- }
- //js方法登录成功
- -(void)jsLoginSuccess:(NSDictionary *)dict {
- NSLog(@"search登录成功提示");
- NSString *status = [NSString stringWithFormat:@"%@",dict[@"status"]];
- [GlobalData shareInstance].isReLogin = YES;
- if([status isEqualToString:@"S"]) {
- if(pushIndex!=0) {
- kMainQueue((^{
- [[NSNotificationCenter defaultCenter] postNotificationName:RefreshAllVC object:nil userInfo:nil];
- AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
- JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
- tab.selectedIndex = pushIndex;
- pushIndex = 0;
- }));
- }else {
- [self webViewFirstRequest];
- }
-
- }else if ([status isEqualToString:@""]) {
- //不刷新订阅-首页,刷新其他
- [[NSNotificationCenter defaultCenter] postNotificationName:RefreshExpAndMine object:nil userInfo:nil];
- }else {
-
- }
- }
- -(void)jsBackUrl:(NSDictionary *)dict {
- NSString *status = [NSString stringWithFormat:@"%@",dict[@"status"]];
- if([status isEqualToString:@"H"]) {
- pushIndex = 0;
- [self webViewFirstRequest];
- }
- }
- -(void)jsClearPushMessage:(NSDictionary *)dict {
- kMainQueue(^{
- [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
- [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
- });
- }
- -(void)jsHideRedSpotOnMenu:(NSDictionary *)dict {
- NSString *menu = [NSString stringWithFormat:@"%@",dict[@"menu"]];
- if([menu isEqualToString:@"subscribe"]) {
- kMainQueue(^{
- [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
- });
- }
- if([menu isEqualToString:@"my"]) {
- kMainQueue(^{
- [self.tabBarController.tabBar hideBadgeOnItemIndex:3];
- });
- }
- }
- -(void)jsShowRedSpotOnMenu:(NSDictionary *)dict {
- NSString *menu = [NSString stringWithFormat:@"%@",dict[@"menu"]];
- if([menu isEqualToString:@"subscribe"]) {
- kMainQueue(^{
- [self.tabBarController.tabBar showBadgeOnItemIndex:1];
- });
- }
- if([menu isEqualToString:@"my"]) {
- kMainQueue(^{
- [self.tabBarController.tabBar showBadgeOnItemIndex:3];
- });
- }
- }
- -(void)jsWxPay:(NSDictionary *)dict {
- NSString *jsonString = [NSString stringWithFormat:@"%@",dict[@"order"]];
- if ([LXUserDefaults isInstallWeiXin] != 1) { // 没有安装wx
- [[LXViewControllerManager shareViewControllerManager] showHudOnlyText:@"请先安装微信再进行支付!" delay:1.5];
- return;
- }
- NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
- NSError *err;
- NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
- if(err) {
- NSLog(@"json解析失败:%@",err);
- return;
- }
- //吊起微信
- PayReq *request = [[PayReq alloc] init] ;
- request.openID = dic[@"Appid"];
- request.partnerId = dic[@"Partnerid"];
- request.prepayId= dic[@"Prepayid"];
- request.package = @"Sign=WXPay";
- request.nonceStr= dic[@"Noncestr"];
- request.timeStamp= [dic[@"Timestamp"] intValue];
- request.sign= dic[@"Sign"];
-
- kMainQueue(^{
- [WXApi sendReq:request];
- });
- }
- -(void)jsAliPay:(NSDictionary *)dict {
- NSString *order = [NSString stringWithFormat:@"%@",dict[@"order"]];
- kMainQueue(^{
- [[AlipaySDK defaultService] payOrder:order fromScheme:@"jianyuiosapp" callback:nil];
- });
-
-
- }
- -(NSString *)jsGetOtherPushRid:(NSDictionary *)dict {
- return [LXUserDefaults deviceToken];
- }
- -(NSString *)jsGetPhoneBrand:(NSDictionary *)dict {
- UIDevice *device = [UIDevice currentDevice];
- return device.platformString;
- }
- -(NSString *)jsGetLocation:(NSDictionary *)dict {
- NSLog(@"------开始调用获取位置");
- if (!self.isLocation) {
- // 1.检查定位服务是否开启
- if ([self checkLocationServiceIsEnabled]) {
- // 2.创建定位管理器:
- [self createCLManager];
- self.isLocation = YES; //只请求一次
- }else{
- NSLog(@"定位不可用");
- self.isLocation = NO;
- }
- NSLog(@"即将返回城市信息-%@",self.placeAdr);
- }
-
- return self.placeAdr;
- }
- -(void)jsChooseTab:(NSDictionary *)dict {
- NSInteger indexTab = [dict[@"indexTab"] integerValue];
- kMainQueue((^{
- AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
- JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
- tab.selectedIndex = indexTab;
- pushIndex = indexTab;
- }));
- }
- //拍照上传图片
- -(void)jsSkipCamera:(NSDictionary *)dict {
-
- UIImagePickerController *picker = [[UIImagePickerController alloc] init];
- picker.delegate = self;
- picker.allowsEditing = YES;
- picker.sourceType = UIImagePickerControllerSourceTypeCamera;
- dispatch_async(dispatch_get_main_queue(), ^{
- [self presentViewController:picker animated:YES completion:nil];
- });
-
-
- }
- //相册选择照片
- -(void)jsSkipAlbum:(NSDictionary *)dict {
-
- UIImagePickerController *picker = [[UIImagePickerController alloc] init];
- picker.delegate = self;
- picker.allowsEditing = YES;
- picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- dispatch_async(dispatch_get_main_queue(), ^{
- [self presentViewController:picker animated:YES completion:nil];
- });
- }
- // web是否可退回上页面
- -(int)jsIsCanBack:(NSString *)str{
- return self.webView.canGoBack ? 1:0;
- }
- //-(void)jsJudgeIsHidden:(NSDictionary *)dict {
- // if([dict objectForKey:@"referer"]) {
- // NSString *current_url = [NSString stringWithFormat:@"%@",dict[@"referer"]];
- // if (![current_url isEqualToString:@""]) {
- // NSLog(@"判断是否需要隐藏:%@",current_url);
- // if([current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/jylab/mainSearch",kHost]]){
- // NSLog(@"需要展示");
- // [self showTabBar];
- // [self showMethodTabBar];
- // }else {
- // NSLog(@"需要隐藏");
- // [self hideTabBar];
- // [self hiddenMethodTabBar];
- // }
- // }
- // }
- //}
- #pragma mark *****其他方法
- -(void)judgeIsHidden {
- NSString *current_url = [self stringByEvaluatingJavaScriptFromString:@"document.location.href"];
- NSLog(@"判断需要隐藏否:%@",current_url);
- if([current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/jylab/mainSearch",kHost]]){
- NSLog(@"需要展示");
- [self showTabBar];
- [self showMethodTabBar];
- }else {
- NSLog(@"需要隐藏");
- [self hideTabBar];
- [self hiddenMethodTabBar];
- }
- }
- -(void)timeFireMethod{
- _timeTick++;
- if(self.webView&¬iFinish) {
- NSString * urlStr = [NSString stringWithFormat:@"%@",self.notiDict[@"info"][@"url"]];
- if (urlStr) {
- if([self.notiDict[@"type"] isEqualToString:@"bid"]) {
- AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
- JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
- tab.selectedIndex = 1;
- [self performSelector:@selector(pushDY:) withObject:self.notiDict[@"info"] afterDelay:1];
- }else {
- [[LXViewControllerManager shareViewControllerManager] showHudText:nil];
- self.afterOpenPushMessage = YES;
- [self performSelector:@selector(requestWebTime:) withObject:self.notiDict afterDelay:1];
- }
- [self.timer invalidate];
- self.timer = nil;
- _timeTick = 0;
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"NotiDict"];
- }
- return;
- }
-
- if (_timeTick == 60) {
- [self.timer invalidate];
- self.timer = nil;
- _timeTick = 0;
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"NotiDict"];
- }
- }
- -(void)pushDY:(NSDictionary *)infoDict
- {
- [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDY" object:nil userInfo:infoDict];
- }
- -(void)requestWebTime:(NSDictionary *)infoDict
- {
- NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"url"]];
- if([infoDict[@"type"] isEqualToString:@"message"]) {
- NSString *url = [NSString stringWithFormat:@"%@",urlStr];
- NSArray * array = [url componentsSeparatedByString:@"=="];
- url = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
- }else if ([infoDict[@"type"] isEqualToString:@"titleMessage"]) {
- NSArray * array = [urlStr componentsSeparatedByString:@"=="];
- urlStr = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- NSString * titleStr = @"消息通知";
- titleStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"title"]];
- if (urlStr&&self.tabBarController.selectedIndex == 0) {
- [self JsOpenExternalLink:@{@"url":urlStr,@"title":titleStr}];
- }
- }else {
- NSString *url = [NSString stringWithFormat:@"%@%@", kHost, urlStr];
- url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
- }
- }
- - (void)hideTabBar {
- kMainQueue(^{
- if (self.tabBarController.tabBar.hidden == YES) {
- return;
- }
- UIView *contentView;
- if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
- contentView = [self.tabBarController.view.subviews objectAtIndex:1];
- else
- contentView = [self.tabBarController.view.subviews objectAtIndex:0];
- 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);
- self.tabBarController.tabBar.hidden = YES;
- });
- }
- - (void)showTabBar{
- kMainQueue(^{
- if (self.tabBarController.tabBar.hidden == NO)
- {
- return;
- }
- UIView *contentView;
- if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
-
- contentView = [self.tabBarController.view.subviews objectAtIndex:1];
-
- else
-
- contentView = [self.tabBarController.view.subviews objectAtIndex:0];
- 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);
- self.tabBarController.tabBar.hidden = NO;
- });
- }
- - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
- {
- __block NSString *resultString = nil;
- __block BOOL finished = NO;
- [self.webView evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
- if (error == nil) {
- if (result != nil) {
- resultString = [NSString stringWithFormat:@"%@", result];
- }
- } else {
- NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
- }
- finished = YES;
- }];
- while (!finished) {
- [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
- }
- return resultString;
- }
- -(void)hiddenMethodTabBar
- {
- kMainQueue(^{
- if (iPhoneX) {
- if (@available(iOS 11.0, *)) {
- self.webView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
- NSLog(@"%@",self.webView)
- }
- }else {
- self.webView.frame = CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT+STATUS_BAR_HEIGHT);
- }
- });
- }
- -(void)showMethodTabBar
- {
- kMainQueue(^{
- if (iPhoneX) {
- if (@available(iOS 11.0, *)) {
- self.webView.frame = CGRectMake(0, 0, WIDTH, HEIGHT-TAB_BAR_HEIGHT);
- }
- }else {
- self.webView.frame = CGRectMake(0, -STATUS_BAR_HEIGHT, WIDTH, HEIGHT-TAB_BAR_HEIGHT+STATUS_BAR_HEIGHT);
- }
- });
- }
- //取消获取照片
- - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
- {
- dispatch_async(dispatch_get_main_queue(), ^{
- [picker dismissViewControllerAnimated:YES completion:^{
- [self uploadUrl:@""];
- }];
- });
- }
- //上传图片
- -(void)uploadPic:(NSData *)data
- {
- NSDictionary * body = @{@"type":@"courseFile"};
- AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
- //ContentType设置
- manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",@"text/plain",nil];
- manager.responseSerializer= [AFHTTPResponseSerializer serializer];
- manager.requestSerializer = [AFHTTPRequestSerializer serializer];
- manager.requestSerializer.timeoutInterval = 15.0f;
- [manager POST:[NSString stringWithFormat:@"%@filemanage/upload",kHost] parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
- //上传的参数(上传图片,以文件流的格式)
- [formData appendPartWithFileData:data
- name:@"courseFile"
- fileName:@"courseFile.jpeg"
- mimeType:@"image/jpeg"];
- } progress:^(NSProgress * _Nonnull uploadProgress) {
-
- CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
- NSLog(@"%.2lf%%", progress);
- } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
- //请求成功的block回调
-
- NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
- NSLog(@"上传成功%@",dic);
-
- if ([dic[@"msg"] isEqualToString:@"ssss"]) {
- [self uploadUrl:dic[@"url"]];
- }else{
- [self uploadUrl:@""];
- }
-
- } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
-
- NSLog(@"上传失败%@",error);
- [self uploadUrl:@""];
-
- }];
-
-
-
- }
- -(void)uploadUrl:(NSString *)url {
- NSString *textJS = [NSString new];
- NSString *methodJS = [NSString new];
-
- if ([url isEqualToString:@""]) {
- textJS = @"hiddenLoading()";
- methodJS =@"hiddenLoading";
- }else{
- textJS = [NSString stringWithFormat:@"uploadImg('%@')",url];
- methodJS = @"uploadImg";
- }
- if ([url isEqualToString:@""]||[textJS isEqualToString:@""]) {
- NSLog(@"空的情况");
- textJS = @"hiddenLoading()";
- methodJS = @"hiddenLoading";
- }
-
-
- NSDictionary *dict = @{@"jsStr":textJS,@"name":methodJS};
- [self performSelector:@selector(uploadJS:) withObject:dict afterDelay:1];
-
- }
- //获取到图片
- - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
- {
- dispatch_async(dispatch_get_main_queue(), ^{
- [picker dismissViewControllerAnimated:YES completion:^{
- UIImage * img=[info objectForKey:UIImagePickerControllerEditedImage];
- NSData *data = UIImageJPEGRepresentation(img, 0.5);
- if (data!=nil) {
- [self uploadPic:data];
- }else{
- NSLog(@"data == nil");
- [self uploadUrl:@""];
- }
- }];
- });
- }
- -(void)uploadJS:(NSDictionary *)dict {
- [self isExitCallToJS:dict[@"jsStr"] withMethodName:dict[@"name"]];
- }
- - (BOOL)checkLocationServiceIsEnabled{
- // 该方法是类方法,和我们创建的管理器没有关系
- if ([CLLocationManager locationServicesEnabled]) {
- return YES;
- }
- return NO;
- }
- - (void)createCLManager{
- // 创建CoreLocation管理对象
- self.locaationManager = [[CLLocationManager alloc]init];
- // 设定定位精准度
- [self.locaationManager setDesiredAccuracy:kCLLocationAccuracyBest];
- // 设定DistanceFilter可以在用户移动指定距离之后触发更新事件(100米更新一次)
- [self.locaationManager setDistanceFilter:100.f];
- // 设置代理
- self.locaationManager.delegate = self;
- // 开始更新定位
- [self.locaationManager startUpdatingLocation];
- }
- // 代理方法,更新位置
- - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
- CLLocation * newLocation = [locations lastObject];
- // 判空处理
- if (newLocation.horizontalAccuracy < 0) {
- return;
- }
- CLGeocoder *geocoder = [[CLGeocoder alloc] init];
- [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
- for (CLPlacemark *placeMark in placemarks) {
- //NSLog(@"位置:%@", placeMark.name);
- //NSLog(@"街道:%@", placeMark.thoroughfare);
- //NSLog(@"子街道:%@", placeMark.subThoroughfare);
- //NSLog(@"区\\县:%@", placeMark.subLocality);
- //NSLog(@"市:%@", placeMark.locality);
- //NSLog(@"行政区:%@", placeMark.administrativeArea);
- //NSLog(@"国家:%@", placeMark.country);
-
- self.placeAdr = [placeMark.administrativeArea stringByAppendingString:[NSString stringWithFormat:@"-%@",placeMark.locality]];
- }
- }];
-
- // [self.locaationManager stopUpdatingLocation];
- // self.locaationManager.delegate=nil;
- // //获取定位经纬度
- // CLLocationCoordinate2D coor2D = newLocation.coordinate;
- // NSLog(@"纬度为:%f, 经度为:%f", coor2D.latitude, coor2D.longitude);
- //
- // // 获取定位海拔高度
- // CLLocationDistance altitude = newLocation.altitude;
- // NSLog(@"高度为:%f", altitude);
- //
- // // 获取定位水平精确度, 垂直精确度
- // CLLocationAccuracy horizontalAcc = newLocation.horizontalAccuracy;
- // CLLocationAccuracy verticalAcc = newLocation.verticalAccuracy;
- // NSLog(@"%f, %f", horizontalAcc, verticalAcc);
- }
- // 代理方法,定位权限检查
- -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
- switch (status) {
- case kCLAuthorizationStatusNotDetermined:{
- NSLog(@"用户还未决定授权");
- // 主动获得授权
- [self.locaationManager requestWhenInUseAuthorization];
- break;
- }
- case kCLAuthorizationStatusRestricted:
- {
- NSLog(@"访问受限");
- // 主动获得授权
- [self.locaationManager requestWhenInUseAuthorization];
- break;
- }
- case kCLAuthorizationStatusDenied:{
- // 此时使用主动获取方法也不能申请定位权限
- // 类方法,判断是否开启定位服务
- if ([CLLocationManager locationServicesEnabled]) {
- NSLog(@"定位服务开启,被拒绝");
- } else {
- NSLog(@"定位服务关闭,不可用");
- }
- break;
- }
- case kCLAuthorizationStatusAuthorizedAlways:{
- NSLog(@"获得前后台授权");
- break;
- }
- case kCLAuthorizationStatusAuthorizedWhenInUse:{
- NSLog(@"获得前台授权");
- break;
- }
- default:
- break;
- }
- }
- -(NSString *)convertToJsonData:(NSDictionary *)dict {
- NSError *error;
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
- NSString *jsonString;
- if (!jsonData) {
- NSLog(@"%@",error);
- }else{
- jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
- }
- NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
- NSRange range = {0,jsonString.length};
- //去掉字符串中的空格
- [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
- NSRange range2 = {0,mutStr.length};
- //去掉字符串中的换行符
- [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
- return mutStr;
- }
- -(void)addNoNetViews{
- kMainQueue(^{
- [self removeNoNetViews];
- self.noNetView = [NoNetView shareView];
- [self.view addSubview:self.noNetView];
- });
- }
- -(void)removeNoNetViews{
- if (self.noNetView ) {
- [self.noNetView removeFromSuperview];
- self.noNetView = nil;
- }
- }
- #pragma mark **** 通知相关方法
- // 点击通知 跳转到通知内url
- -(void)requestWebView:(NSNotification *)notification{
- NSDictionary * infoDict = [notification object];
- if (!infoDict) {
- return;
- }
- NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"info"][@"url"]];
- if (urlStr) {
- //当前控制器
- if(self.tabBarController.selectedIndex != 0) {
- return;
- }
- [[LXViewControllerManager shareViewControllerManager] showHudText:nil];
- self.afterOpenPushMessage = YES;
- [self performSelector:@selector(requestWebTime:) withObject:infoDict afterDelay:1];
- }
- }
- -(void)clickSubNotiMethods:(NSNotification *)notification{
- NSDictionary * infoDict = [notification object][@"info"];
- if (!infoDict) {
- return;
- }
- NSLog(@"%@",infoDict);
- NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"url"]];
- if (urlStr) {
- NSLog(@"有info");
- if(self.tabBarController.selectedIndex == 0) {
- //底部栏置换到订阅
- AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
- JYTabBarController *tab = (JYTabBarController *)delegate.window.rootViewController;
- tab.selectedIndex = 1;
- [self performSelector:@selector(pushDY:) withObject:infoDict afterDelay:1];
- }
- }
- }
- //点击支付通知
- -(void)clickPayMethods:(NSNotification *)notification{
- NSDictionary * infoDict = [notification object][@"info"];
- if (!infoDict) {
- return;
- }
- NSString * urlStr = [NSString stringWithFormat:@"%@",infoDict[@"url"]];
- NSArray * array = [urlStr componentsSeparatedByString:@"=="];
- urlStr = [array.firstObject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- NSString * titleStr = @"消息通知";
- titleStr = [NSString stringWithFormat:@"%@",infoDict[@"title"]];
- if (urlStr) {
- if(self.tabBarController.selectedIndex == 0) {
- [self JsOpenExternalLink:@{@"url":urlStr,@"title":titleStr}];
- }
- }
- }
- -(void)alipayWXpayStatus:(NSNotification *)notification{
-
- NSString * status = [notification object];
- [self performSelector:@selector(payStatus:) withObject:status afterDelay:2];
- }
- -(void)payStatus:(NSString *)status
- {
- //目前延时两秒
- NSLog(@"支付状态:%@",status);
- if(self.tabBarController.selectedIndex == 0) {
- [self isExitCallToJS:[NSString stringWithFormat:@"payCallBack('%@')", status] withMethodName:@"payCallBack"];
- }
-
- }
- // 调用js方法 刷新推送权限状态
- -(void)updateNotifyState{
- if (self.updateNotify) {
- self.updateNotify = NO;
- [self isExitCallToJS:[NSString stringWithFormat:@"updateNoticeSwitch()"] withMethodName:@"updateNoticeSwitch"];
- }
- }
- // 收到通知消息
- -(void)afterReceiveNewMsg{
- NSLog(@"afterReceiveNewMsg");
- [self isExitCallToJS:@"afterReceiveNewMsg()" withMethodName:@"afterReceiveNewMsg"];
- }
- // 再次加载页面
- -(void)reloadWebView{
- if(self.tabBarController.selectedIndex == 0) {
- [[LXViewControllerManager shareViewControllerManager] showHudText:nil];
- if (!self.webView.canGoBack) {
- [self webViewFirstRequest];
- }else{
- [self.webView reload];
- }
- }
- }
- // 收到退出登录消息
- -(void)loginOut:(NSNotification *)notification{
- if([notification.userInfo[@"item_index"] integerValue]!=0) {
- return;
- }
- [self webViewRequestByMsg];
-
- }
- //收到消息退出并重新加载web
- -(void)webViewRequestByMsg{
- NSString *url = [NSString stringWithFormat:@"%@%@", kHost, @"jyapp/free/login?back=index&isios=t&flag=kicked"];
- url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
- }
- // 监控网络状态变化
- -(void)netReachChanged:(NSNotification *)notificaition{
- NSDictionary *userInfo = notificaition.userInfo;
- if ([userInfo[@"AFNetworkingReachabilityNotificationStatusItem"] intValue] == 0 || [userInfo[@"AFNetworkingReachabilityNotificationStatusItem"] intValue] == -1) {
- [self addNoNetViews];
- }else{
- [self removeNoNetViews];
- }
- }
- //前往登录页面
- -(void)isLoginTabBar:(NSNotification *)notification
- {
- NSDictionary *dict = notification.userInfo;
- NSLog(@"我从第几个页面过来:%@",dict[@"item_index"]);
- pushIndex = [dict[@"item_index"] integerValue];
- NSString *url = [NSString stringWithFormat:@"%@%@", kHost, @"jyapp/free/login"];
- url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
-
- }
- -(void)newsRedPoint:(NSNotification *)notificaition
- {
- NSDictionary *dict = notificaition.userInfo;
- NSLog(@"%@",dict);
- NSInteger type = [dict[@"type"] integerValue];
- if(type==1) {
- //显示
- kMainQueue(^{
- [self.tabBarController.tabBar showBadgeOnItemIndex:1];
- });
- }else if (type==2) {
- //显示
- kMainQueue(^{
- [self.tabBarController.tabBar showBadgeOnItemIndex:3];
- });
- }else {
-
- }
-
- if(self.tabBarController.selectedIndex == 0) {
- NSString *textJS = [NSString stringWithFormat:@"afterReceivePushMessage('%@','%@')",dict[@"typeMsg"],dict[@"url"]];
- [self isExitCallToJS:textJS withMethodName:@"afterReceivePushMessage"];
- }
- }
- //刷新页面相关
- -(void)refreshNonCurVC:(NSNotification *)notificaition{
- if(self.tabBarController.selectedIndex != 0) {
- refreshTabBool = YES;
- [self webViewFirstRequest];
- }
- }
- -(void)refreshAllVC:(NSNotification *)notificaition{
- [self webViewFirstRequest];
- }
- -(void)clearWeb{
- NSURLCache * cache = [NSURLCache sharedURLCache];
- [cache removeAllCachedResponses];
- [cache setDiskCapacity:0];
- [cache setMemoryCapacity:0];
-
- }
- /*
- #pragma mark - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
- // Get the new view controller using [segue destinationViewController].
- // Pass the selected object to the new view controller.
- }
- */
- @end
|