123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830 |
- //
- // 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,CLLocationManagerDelegate,SKProductsRequestDelegate,SKPaymentTransactionObserver>
- {
- NSInteger _timeTick;
- NSInteger _time;
- NSInteger pushIndex;//第几个模块过来的
- BOOL notiFinish;
- 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,strong)CLLocationManager *locaationManager;
- @property(nonatomic,strong)NSString *placeAdr;
- @property(nonatomic,assign)BOOL isLocation;
- @property(nonatomic, strong)NoNetView *noNetView;
- @property(nonatomic, strong)UIPanGestureRecognizer *recognizer;
- @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.allowsInlineMediaPlayback = YES;
- 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",
- @"openActivityPage",
- @"callPhone",
- @"openOtherAppLinks",
- @"inPurchasingVip",
- ];
- 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.userInteractionEnabled = YES;
- [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
- }
- return _webView;
- }
- -(void)webViewFirstRequest
- {
- //去时间戳-拼接
- NSString *url = [NSString stringWithFormat:@"%@jyapp/free/index?deviceid=%@", kHost, [LXUserDefaults getDeviceID]];
- NSString *token = [LXUserDefaults token];
- if ([LXUserDefaults isExistToken]) {
- 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) {
- self.recognizer.enabled = YES;
- [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];
-
- //前往登录通知-tabbar
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isLoginTabBar:) name:LoginIndexTabBar 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]||([current_url containsString:@"jyapp/free/login"])) {
- NSLog(@"不可返回");
- return;
- }
- 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;
- }
- CGPoint touchPoint = [recoginzer locationInView:[UIApplication sharedApplication].keyWindow];
- if (recoginzer.state==UIGestureRecognizerStateBegan) {
- _isMoving = YES;
- startTouch = touchPoint;
- } else if (recoginzer.state==UIGestureRecognizerStateEnded||(recoginzer.state==UIGestureRecognizerStatePossible)){
- if (touchPoint.x - startTouch.x > width*0.125) {
- [UIView animateWithDuration:0.3 animations:^{
- [self moveViewWithX:width];
- if ([current_url containsString:@"jyapp/jylab/mainSearch#"]) {
- [self isExitCallToJS:@"afterClickBack()" withMethodName:@"afterClickBack"];
- }
- // [self.webView goBack];
-
- NSString *jsStr = @"window.history.back()";
- [self executeCallJS:jsStr];
-
- } 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;
- }else {
-
- }
- 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 if ([message.name isEqualToString:@"openActivityPage"]) {
- [self jsOpenActivityPage:message.body];
- }else if ([message.name isEqualToString:@"callPhone"]) {
- [self jsCallPhone:message.body];
- }else if ([message.name isEqualToString:@"openOtherAppLinks"]) {
- [self jsOpenOtherAppLinks:message.body];
- }else if ([message.name isEqualToString:@"inPurchasingVip"]) {
- [self jsInPurchasingVip: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 {
- //如果当前页面是三级页面-
- NSString *curUrl = [webView.URL absoluteString];
- if ([curUrl containsString:@"jyapp/article/content"]) {
- //当前页面是三级页面--判断待跳转页面是否符合内置跳转
- NSString *nextUrl = [navigationAction.request.URL absoluteString];
- if ([nextUrl containsString:@"jianyu360.com"]||[nextUrl containsString:@"jianyu360.cn"]||[nextUrl containsString:@"qmx.top"]) {
- // 允许跳转
- decisionHandler(WKNavigationActionPolicyAllow);
- }else {
- NSLog(@"不允许内部跳转:-%@",nextUrl);
- //筛选拦截-压缩包等格式不允许跳转
- 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"]) {
- // 不允许跳转
- decisionHandler(WKNavigationActionPolicyCancel);
- }else {
- JYNewWebController *ctr = [[JYNewWebController alloc] init];
- ctr.url = nextUrl;
- ctr.titleShow = @"公告信息";
- kMainQueue(^{
- [self presentViewController:ctr animated:NO completion:nil];
- });
- // 不允许跳转-并跳转新页面
- decisionHandler(WKNavigationActionPolicyCancel);
- }
- }
- }else {
- // 允许跳转
- decisionHandler(WKNavigationActionPolicyAllow);
- }
-
-
-
- }
- #pragma mark ****WKUIDelegate
- //通过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];
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [_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);
- [[GlobalData shareInstance] addOnePlistData:@{
- @"detail":[[self stringByEvaluatingJavaScriptFromString:@"document.location.href"] stringByAppendingString:[NSString stringWithFormat:@"\nJS异常方法:%@\n%@",jsStr,[error description]]],
- @"reqTime":[NSNumber numberWithInt:0],
- }];
-
- [[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];
-
- self.recognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(paningGestureReceive:)];
- [self.recognizer delaysTouchesBegan];
- [self.view addGestureRecognizer:self.recognizer];
-
- //初始化临时属性
- self.placeAdr = [NSString new];
-
-
- //定时器-检测错误数据是否超过10个 发送
- [NSTimer scheduledTimerWithTimeInterval:180 target:self selector:@selector(errorLogListening) userInfo:nil repeats:YES];
- //监听底部栏
- [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(bottomOneListening) userInfo:nil repeats:YES];
-
-
- //监听购买结果
- [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
-
-
- }
- -(void)bottomOneListening {
- if(self.tabBarController.selectedIndex == 0) {
- [self judgeIsHiddenBottom];
- }
- }
- - (BOOL)isTheCurrentPeriod{
- NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
- NSDate *now = [NSDate date];
- NSDateComponents *comps = [[NSDateComponents alloc] init];
- NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
- comps = [calendar components:unitFlags fromDate:now];
- long hour = (long)[comps hour];
- if (hour>=12&&hour<14) {
- return YES;
- }
- if (hour>=17&&hour<=23) {
- return YES;
- }
- if (hour>=0&&hour<7) {
- return YES;
- }
- return NO;
- }
- - (NSString *)toJsonStrWithArray:(NSArray *)arr {
- if ([arr isKindOfClass:[NSString class]]) {
- return (NSString *)arr;
- }
- NSError *parseError = nil;
- NSData *data = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
- NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
- jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
- if (parseError) {
- jsonStr = @"";
- }
- return jsonStr;
- }
- -(void)errorLogListening {
- if ([self isTheCurrentPeriod]) {
- if ([[GlobalData shareInstance] getPlistCount]>=50) {
- NSMutableDictionary *dict =[[GlobalData shareInstance] getPlistAllData];
- [[LXNetworkManager shareLXNetworkManager]postWithURLStr:[NSString stringWithFormat:@"%@jyapp/errLogs/Receive",kHost] parameters:@{@"jsonData":[self toJsonStrWithArray:dict[@"jsonData"]]} progress:^(NSProgress *progress) {
- NSLog(@"%@",progress);
- } success:^(id responseObject) {
- NSLog(@"responseObject=%@",responseObject);
- [[GlobalData shareInstance] clearPlistData];
- } failure:^(NSError *error) {
- NSLog(@"error=%@",error);
- [[GlobalData shareInstance] addOnePlistData:@{
- @"detail":[NSString stringWithFormat:@"上传日志接口:%@",[error description]],
- @"reqTime":[NSNumber numberWithInt:0],
- }];
- }];
- }
- }else {
-
- }
- }
- -(void)initApnsTimer {
- //定时器
- if([LXUserDefaults isExistToken]) {
- self.notiDict = [[NSMutableDictionary alloc]initWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:RemoteNotifications]];
- 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 ([LXUserDefaults isExistToken]) {
- [[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);
- [[GlobalData shareInstance] addOnePlistData:@{
- @"detail":[NSString stringWithFormat:@"获取小红点接口:%@",[error description]],
- @"reqTime":[NSNumber numberWithInt:0],
- }];
- }];
- }
- }
- #pragma mark - WKNavigationDelegate
- /* 页面加载完成 */
- - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
- // NSLog(@"-----页面加载完成%@",webView.URL.absoluteString);
- //第一次加载小红点
- if(!isLoadRedDot) {
- isLoadRedDot = true;
- [self haveRedPoint];
- }
- if(!notiFinish) {
- notiFinish = YES;
- }
- [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
- [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
- [self judgeIsHiddenBottom];//是否隐藏
- [self removeNoNetViews];
- [[LXViewControllerManager shareViewControllerManager] hideHud];
- //写数据
- // [self writeWKWebData:webView.URL];
- }
- -(void)writeWKWebData:(NSURL *)url {
- //得到NSData 数据
- NSData *dataContent = [NSData dataWithContentsOfURL:url];
- //NSURLCache 实例化
- NSURLCache *cache = [NSURLCache sharedURLCache];
- //得到相应
- NSURLResponse *response = [[NSURLResponse alloc]initWithURL:url MIMEType:nil expectedContentLength:0 textEncodingName:@"UTF-8"];
- //得到CacheURLResponse
- NSCachedURLResponse *cacheResponse = [[NSCachedURLResponse alloc]initWithResponse:response data:dataContent];
- //进行存储
- [cache storeCachedResponse:cacheResponse forRequest:[NSURLRequest requestWithURL:url]];
- }
- // 页面开始加载时调用
- - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
- self.recognizer.enabled = NO;
- }
- // 当内容开始返回时调用
- - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
- }
- // 页面加载失败时调用
- - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(nonnull NSError *)error{
- self.recognizer.enabled = YES;
- [[GlobalData shareInstance] addOnePlistData:@{
- @"detail":[[self stringByEvaluatingJavaScriptFromString:@"document.location.href"] stringByAppendingString:[NSString stringWithFormat:@"\n%@",[error description]]],
- @"reqTime":[NSNumber numberWithInt:0],
- }];
- }
- #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];
- }];
- }
- // 处理微信登录获取到的数据
- -(void)dealWXDic:(NSDictionary *)dictionary{
- //如果获取到用户信息,即用户点击了“登录”,则进行用户信息获取
- 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{
- [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) {
- }
- JYNewWebController *ctr = [[JYNewWebController 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{
- NSDictionary *objDict = [NSDictionary dictionaryWithDictionary:dict[@"arguments"]];
- NSString *phone = [NSString stringWithFormat:@"%@",objDict[@"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(@"------开始调用获取位置:%@",self.placeAdr);
- if (!self.isLocation) {
- // 1.检查定位服务是否开启
- if ([self checkLocationServiceIsEnabled]) {
- // 2.创建定位管理器:
- NSLog(@"定位可用");
- [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];
- });
- }
- //统计点击推送
- -(void)jsOpenActivityPage:(NSDictionary *)dict {
- NSDictionary * infoDic = @{@"url":[NSString stringWithFormat:@"%@",dict[@"url"]],
- @"rectype":[NSString stringWithFormat:@"%@",dict[@"rectype"]],
- @"openid":[NSString stringWithFormat:@"%@",dict[@"openid"]],
- };
- //post请求
- NSLog(@"%@",[NSString stringWithFormat:@"%@jyapp/free/message/receive",kHost]);
- [[LXNetworkManager shareLXNetworkManager]postWithURLStr:[NSString stringWithFormat:@"%@jyapp/free/message/receive",kHost] parameters:infoDic progress:^(NSProgress *progress) {
- NSLog(@"成功:%@",progress);
- } success:^(id responseObject) {
- NSLog(@"responseObject=%@",responseObject);
- } failure:^(NSError *error) {
- NSLog(@"error=%@",error);
- [[GlobalData shareInstance] addOnePlistData:@{
- @"detail":[NSString stringWithFormat:@"message/receive接口:%@",[error description]],
- @"reqTime":[NSNumber numberWithInt:0],
- }];
- }];
-
- }
- //拨打电话
- -(void)jsCallPhone:(NSDictionary *)dict {
- NSString *phone = [NSString stringWithFormat:@"%@",dict[@"phone"]];
- NSMutableString *tel = [[NSMutableString alloc]initWithFormat:@"telprompt://%@",phone];
- if (@available(iOS 10.0, *)) {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel] options:@{} completionHandler:^(BOOL success) {
- }];
- } else {
- // Fallback on earlier versions
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel]];
- }
- }
- //打开其他app 抖音+快手
- -(void)jsOpenOtherAppLinks:(NSDictionary *)dict {
- //测试跳转抖音--快手 @"gifshow://" @"snssdk1128://"
- NSString *appLink = [NSString stringWithFormat:@"%@",dict[@"appLink"]];
- NSString *appName = [NSString stringWithFormat:@"%@",dict[@"appName"]];
- NSLog(@"appName:%@",appName);
- NSURL *url = [NSURL URLWithString:appLink];
- if ([[UIApplication sharedApplication] canOpenURL:url]) {
- if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
- //iOS 10.0+
- NSLog(@"iOS 10+");
- if (@available(iOS 10.0, *)) {
- [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
- if (!success) {
- [[LXDataBaseManager shareDataBaseManager]showHudOnlyText:appName delay:2];
- }
- }];
- } else {
- // Fallback on earlier versions
- [[UIApplication sharedApplication] openURL:url];
- }
- }else{
- NSLog(@"iOS 2~10");
- //iOS 2~10
- [[UIApplication sharedApplication] openURL:url];
- }
- }else{
- //一般是没有安装
- NSLog(@"跳转下载app链接");
- [[LXDataBaseManager shareDataBaseManager]showHudOnlyText:appName delay:2];
- }
- }
- //内购VIP
- -(void)jsInPurchasingVip:(NSDictionary *)dict {
- NSString *productid = [NSString stringWithFormat:@"%@",dict[@"productid"]];
- //产品id
- if ([productid isEqualToString:@""]) {
- NSLog(@"订单号 有问题");
- [[LXDataBaseManager shareDataBaseManager]showHudOnlyText:@"订单号异常,请重试" delay:1];
- return;
- }
- [[LXViewControllerManager shareViewControllerManager] showHudText:@"苹果验证中,请稍候"];
- //监听购买结果
- if([SKPaymentQueue canMakePayments]){
- [self requestProductData:productid];
- }else{
- NSLog(@"不允许程序内付费");
- [[LXViewControllerManager shareViewControllerManager] hideHud];
- }
- }
- //去苹果服务器请求商品
- - (void)requestProductData:(NSString *)type {
- NSArray *product = [[NSArray alloc] initWithObjects:type,nil];
- NSSet *nsset = [NSSet setWithArray:product];
- SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
- request.delegate = self;
- [request start];
- }
- - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
- NSArray *myProduct = response.products;
- if (myProduct.count == 0) {
- NSLog(@"无法获取产品信息,购买失败。");
- [[LXViewControllerManager shareViewControllerManager]showHudOnlyText:@"暂时未获取到产品信息,请重试" delay:1];
- return;
- }
- SKPayment * payment = [SKPayment paymentWithProduct:myProduct[0]];
- [[SKPaymentQueue defaultQueue] addPayment:payment];
- }
-
- //监听购买结果
- - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
- // NSLog(@"收到支付回调");
- for (SKPaymentTransaction *transaction in transactions) {
- switch (transaction.transactionState) {
- case SKPaymentTransactionStatePurchased://交易完成
- NSLog(@"购买成功transactionIdentifier = %@", transaction.transactionIdentifier);
- [self completeTransaction:transaction];
- break;
- case SKPaymentTransactionStateFailed://交易失败
- [self failedTransaction:transaction];
- break;
- case SKPaymentTransactionStateRestored://已经购买过该商品
- [self restoreTransaction:transaction];
- break;
- case SKPaymentTransactionStatePurchasing://商品添加进列表
- NSLog(@"商品添加进列表");
- break;
- default:
- break;
- }
- }
- }
- - (void)completeTransaction:(SKPaymentTransaction *)transaction {
- // Your application should implement these two methods.
- [[LXViewControllerManager shareViewControllerManager] hideHud];
- NSString * productIdentifier = transaction.payment.productIdentifier;
- NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[[NSBundle mainBundle] appStoreReceiptURL]];
- NSData *receiptData;
- NSError *error = nil;
- receiptData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&error];
- NSString *receipt = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
- if ([productIdentifier length] > 0) {
- // 向自己的服务器验证购买凭证
- if(self.tabBarController.selectedIndex == 0) {
- [self isExitCallToJS:[NSString stringWithFormat:@"getReceipt('%@')", receipt] withMethodName:@"getReceipt"];
- }else {
- [[NSNotificationCenter defaultCenter] postNotificationName:@"receiptData" object:nil userInfo:@{@"receipt":receipt}];
- }
- }
- // Remove the transaction from the payment queue.
- [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
-
- }
- - (void)failedTransaction:(SKPaymentTransaction *)transaction {
- [[LXViewControllerManager shareViewControllerManager] hideHud];
- if(transaction.error.code != SKErrorPaymentCancelled) {
- NSLog(@"购买失败");
- [[LXViewControllerManager shareViewControllerManager]showHudOnlyText:@"购买失败,请重新尝试。" delay:1];
- } else {
- NSLog(@"用户取消交易");
- [[LXViewControllerManager shareViewControllerManager]showHudOnlyText:@"取消交易" delay:1];
- }
- [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
- }
- - (void)restoreTransaction:(SKPaymentTransaction *)transaction {
- // 对于已购商品,处理恢复购买的逻辑
- NSLog(@"对于已购商品,处理恢复购买的逻辑");
- [[LXViewControllerManager shareViewControllerManager] hideHud];
- [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
- }
- // web是否可退回上页面
- -(int)jsIsCanBack:(NSString *)str{
- return self.webView.canGoBack ? 1:0;
- }
- #pragma mark *****其他方法
- -(void)judgeIsHiddenBottom {
- if(self.tabBarController.selectedIndex == 0) {
- NSString *current_url = [self stringByEvaluatingJavaScriptFromString:@"document.location.href"];
- NSArray *array = [current_url componentsSeparatedByString:@"?"];
- current_url = [NSString stringWithFormat:@"%@",array.firstObject];
- if([current_url isEqualToString:[NSString stringWithFormat:@"%@jyapp/jylab/mainSearch",kHost]]){
- [self showTabBar];
- [self showMethodTabBar];
- }else {
- [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 {
- [self performSelector:@selector(requestWebTime:) withObject:self.notiDict afterDelay:1];
- }
- [self.timer invalidate];
- self.timer = nil;
- _timeTick = 0;
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:RemoteNotifications];
- }
- return;
- }
-
- if (_timeTick == 60) {
- [self.timer invalidate];
- self.timer = nil;
- _timeTick = 0;
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:RemoteNotifications];
- }
- }
- -(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);
- }
- }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:@""];
-
- [[GlobalData shareInstance] addOnePlistData:@{
- @"detail":@"上传图片接口",
- @"reqTime":[NSNumber numberWithInt:0],
- }];
-
-
- }];
-
-
-
- }
- -(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:1.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]];
- }
- }];
- }
- // 代理方法,定位权限检查
- -(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;
- }
- [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) {
- 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) {
- [self webViewFirstRequest];
- }
- }
- -(void)refreshAllVC:(NSNotification *)notificaition{
- [self webViewFirstRequest];
- }
- -(void)clearWeb{
- NSURLCache * cache = [NSURLCache sharedURLCache];
- [cache removeAllCachedResponses];
- [cache setDiskCapacity:0];
- [cache setMemoryCapacity:0];
-
- }
- - (void)clearCache {
- /* 取得Library文件夹的位置*/
- NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)[0];
- /* 取得bundle id,用作文件拼接用*/
- NSString *bundleId = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleIdentifier"];
- /*
- * 拼接缓存地址,具体目录为App/Library/Caches/你的APPBundleID/fsCachedData
- */
- NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
- NSError *error;
- /* 取得目录下所有的文件,取得文件数组*/
- NSFileManager *fileManager = [NSFileManager defaultManager];
- // NSArray *fileList = [[NSArray alloc] init];
- //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
- NSArray *fileList = [fileManager contentsOfDirectoryAtPath:webKitFolderInCachesfs error:&error];
- /* 遍历文件组成的数组*/
- for(NSString * fileName in fileList){
- /* 定位每个文件的位置*/
- NSString * path = [[NSBundle bundleWithPath:webKitFolderInCachesfs] pathForResource:fileName ofType:@""];
- /* 将文件转换为NSData类型的数据*/
- NSData * fileData = [NSData dataWithContentsOfFile:path];
- /* 如果FileData的长度大于2,说明FileData不为空*/
- if(fileData.length >2){
- /* 创建两个用于显示文件类型的变量*/
- int char1 =0;
- int char2 =0;
- [fileData getBytes:&char1 range:NSMakeRange(0,1)];
- [fileData getBytes:&char2 range:NSMakeRange(1,1)];
- /* 拼接两个变量*/
- NSString *numStr = [NSString stringWithFormat:@"%i%i",char1,char2];
- /* 如果该文件前四个字符是6033,说明是Html文件,删除掉本地的缓存*/
- if([numStr isEqualToString:@"6033"]){
- [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@",webKitFolderInCachesfs,fileName]error:&error];
- continue;
- }
- }
- }
- }
- /*
- #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
|