123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876 |
- #import "KSBaseWKWebViewController.h"
- #import "JPUSHService.h"
- #import "LoginViewController.h"
- #import "AppDelegate.h"
- #import "CustomNavViewController.h"
- #import <RongIMKit/RongIMKit.h>
- #import "UIDevice+TFDevice.h"
- #import "KSPremissionAlert.h"
- #import "RecordCheckManager.h"
- #import "KSLocalWebViewController.h"
- #import "RCConnectionManager.h"
- #import "KSAccompanyWebViewController.h"
- #import "KSChatConversationViewController.h"
- #import "KSOrderManager.h"
- @interface KSBaseWKWebViewController ()
- @property (nonatomic, assign) BOOL isOutLink;
- @property (nonatomic,weak) CALayer *progressLayer;
- @property (nonatomic, strong) NSString *currerntURL;
- @property (nonatomic, assign) BOOL hasModify;
- @property (nonatomic, assign) BOOL hasChangeSource;
- @property (nonatomic, assign) BOOL landScape;
- @end
- @implementation KSBaseWKWebViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
-
- self.ks_prefersNavigationBarHidden = YES;
- [self initWebView];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(operationDealCallbackMessage:) name:DEALCALLBACKNOTICIFATION object:nil];
- }
- - (void)operationDealCallbackMessage:(NSNotification *)notification {
- NSString *status = [notification object];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"paymentOperation" forKey:@"api"];
- [sendParm setValue:status forKey:@"status"];
- [self postMessage:sendParm];
- }
- - (void)setParmDic:(NSDictionary *)parmDic {
- _parmDic = parmDic;
- _hasChangeSource = YES;
- BOOL isOpenLight = [parmDic boolValueForKey:@"isOpenLight"];
- [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
-
- NSInteger orientation = [parmDic integerValueForKey:@"orientation"];
-
- BOOL isLandScape = orientation == 0 ? YES : NO;
- if (_landScape != isLandScape) {
- [self changeOrientation:isLandScape];
- }
-
- self.hideTop = [parmDic boolValueForKey:@"isHideTitle"];
- }
- - (void)changeOrientation:(BOOL)isLandScape {
- self.landScape = isLandScape;
- if (isLandScape) {
-
- AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
- delegate.allowAutoRotate = YES;
- [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
- }
- else {
- AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
- delegate.allowAutoRotate = NO;
- [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
- }
- }
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- if (_hasChangeSource) {
- [self setParmDic:self.parmDic];
- }
- }
- - (void)viewWillDisappear:(BOOL)animated {
- [super viewWillDisappear:animated];
- if (_hasChangeSource && self.keepOrientation == NO && self.landScape == YES) {
- [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
- [self changeOrientation:NO];
- }
- self.keepOrientation = NO;
- }
- - (void)initWebView {
-
- [self.view addSubview:self.navView];
- CGFloat topHeight = kNaviBarHeight;
- if (self.hideTop) {
- topHeight = 0.0f;
- }
- [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.top.mas_equalTo(self.view);
- make.height.mas_equalTo(topHeight);
- }];
-
- [self.view addSubview:self.webBackButton];
- [self.webBackButton mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.top.mas_equalTo(self.view);
- make.height.mas_equalTo(kNaviBarHeight);
- make.width.mas_equalTo(44);
- }];
- if (self.hideTop) {
- self.webBackButton.hidden = YES;
- }
- if (_hiddenNavBar) {
- topHeight = 0.0f;
- }
- if (self.headTitle) {
- [self.navView.topTitleLabel setText:_headTitle];
- }
-
- if (_myWebView == nil) {
-
- WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
- config.selectionGranularity = WKSelectionGranularityDynamic;
- config.allowsInlineMediaPlayback = YES;
- if (@available(iOS 10.0, *)) {
- config.mediaTypesRequiringUserActionForPlayback = NO;
- } else {
-
- config.requiresUserActionForMediaPlayback = NO;
- }
- config.processPool = [KSBaseWKWebViewController singleWkProcessPool];
- config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
-
- WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
-
- WKUserContentController * wkUController = [[WKUserContentController alloc] init];
- [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"COLEXIU"];
- config.userContentController = wkUController;
-
- WKPreferences *preferences = [WKPreferences new];
-
- preferences.javaScriptEnabled = YES;
-
- preferences.javaScriptCanOpenWindowsAutomatically = YES;
- config.preferences = preferences;
- _myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
- _myWebView.UIDelegate = self;
- _myWebView.navigationDelegate = self;
- _myWebView.scrollView.bounces = NO;
- _myWebView.scrollView.showsVerticalScrollIndicator = NO;
- _myWebView.scrollView.showsHorizontalScrollIndicator = NO;
-
- [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
- [_myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
- [self.view addSubview:_myWebView];
- [_myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.mas_equalTo(self.view);
- make.top.mas_equalTo(self.view.mas_top).offset(topHeight);
- make.bottom.mas_equalTo(self.view.mas_bottom).offset(-iPhoneXSafeBottomMargin);
- }];
- if (@available(iOS 11.0, *)) {
- _myWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
- } else {
-
- }
- [self setupProgress];
-
- [self setUserAgent];
-
- [self.view bringSubviewToFront:self.navView];
- [self.view bringSubviewToFront:self.webBackButton];
- }
- else {
- [_myWebView reload];
- }
- }
- - (void)setUserAgent {
- MJWeakSelf;
- [self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
- NSString *oldUserAgent = result;
- NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@",oldUserAgent,@"COLEXIUAPPI"];
- weakSelf.myWebView.customUserAgent = newUserAgent;
- [weakSelf loadRequest];;
- }];
- }
- - (void)loadRequest {
- MJWeakSelf;
- [self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
- NSLog(@"%@",result);
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:weakSelf.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
- [weakSelf.myWebView loadRequest:request];
- }];
- }
- - (NSString *)url {
- if (_url) {
- if ([_url containsString:@"Authorization="]) {
- NSRange range = [_url rangeOfString:@"Authorization="];
- if (range.location != NSNotFound) {
- _url = [_url substringToIndex:range.location-1];
- }
- }
- NSString *sepectString = [_url containsString:@"?"] ? @"&" : @"?";
- NSString *tokenStr = UserDefault(TokenKey);
- if (![NSString isEmptyString:tokenStr]) {
- NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- _url = [NSString stringWithFormat:@"%@%@%@",_url, sepectString, token];
- }
- }
- return _url;
- }
- #pragma mark --- 返回按钮的处理
- - (void)backAction {
- [self.myWebView stopLoading];
- if (_backRootView) {
- [self.navigationController popToRootViewControllerAnimated:NO];
- return;
- }
- else if (_isBackPreView) {
- [self.navigationController popViewControllerAnimated:YES];
- return;
- }
- else if ([self.myWebView canGoBack]) {
- [self.myWebView goBack];
- }
- else {
- [self.navigationController popViewControllerAnimated:YES];
- }
- }
- #pragma mark - WKScriptMessageHandler
- - (void)userContentController:(WKUserContentController *)userContentController
- didReceiveScriptMessage:(WKScriptMessage *)message {
- if ([message.name isEqualToString:@"COLEXIU"]) {
- NSDictionary *parm = [self convertJsonStringToNSDictionary:message.body];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [self handleScriptMessageSource:parm];
- });
- }
- }
- - (void)handleScriptMessageSource:(NSDictionary *)parm {
- if ([[parm stringValueForKey:@"api"] isEqualToString:@"back"]) {
- [self.navigationController popViewControllerAnimated:YES];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"login"]) {
-
- [self backLoginView];
- }
-
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openConversationActivity"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
- NSString *name = [valueDic stringValueForKey:@"name"];
- NSString *userId = [NSString stringWithFormat:@"%.0f",[valueDic floatValueForKey:@"userId"]];
- KSChatConversationViewController *conversationVC = [[KSChatConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:[NSString returnNoNullStringWithString:userId]];
- conversationVC.title = [NSString returnNoNullStringWithString:name];
- [self.navigationController pushViewController:conversationVC animated:YES];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openWebView"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
-
- KSBaseWKWebViewController *detailCtrl = [[KSBaseWKWebViewController alloc] init];
- detailCtrl.url = [valueDic stringValueForKey:@"url"];
- detailCtrl.parmDic = valueDic;
- NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
- BOOL isLandScape = orientation == 0 ? YES : NO;
- if (isLandScape == self.landScape) {
- self.keepOrientation = YES;
- detailCtrl.keepOrientation = YES;
- }
- [self postMessage:parm];
- [self.navigationController pushViewController:detailCtrl animated:YES];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"setRequestedOrientation"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
-
- NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
- BOOL isLandScape = orientation == 0 ? YES : NO;
- [self changeOrientation:isLandScape];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"keepScreenLongLight"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
- BOOL isOpenLight = [valueDic boolValueForKey:@"isOpenLight"];
- [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"downLoad"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
- if ([valueDic stringValueForKey:@"PDF"]) {
- NSString *url = [valueDic stringValueForKey:@"downloadUrl"];
- [KSNetworkingManager downloadFileRequestWithFileUrl:url progress:^(int64_t bytesRead, int64_t totalBytes) {
- } success:^(NSURL * _Nonnull fileUrl) {
- MJWeakSelf;
- [self KSShowMsg:@"下载成功" promptCompletion:^{
- [weakSelf displaySource:fileUrl];
- }];
- } faliure:^(NSError * _Nonnull error) {
- }];
- }
- }
-
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"isSpecialShapedScreen"]) {
- BOOL isShapedScreen = iPhoneXSafeTopMargin > 0 ? YES : NO;
- NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm dictionaryValueForKey:@"content"]];
- [valueDic setValue:@(isShapedScreen) forKey:@"isSpecialShapedScreen"];
- [valueDic setValue:@(iPhoneXSafeTopMargin*2) forKey:@"notchHeight"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
- [sendParm setValue:valueDic forKey:@"content"];
- [self postMessage:sendParm];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"getToken"]) {
- NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm dictionaryValueForKey:@"content"]];
- [valueDic setValue:UserDefault(Token_type) forKey:@"tokenType"];
- [valueDic setValue:UserDefault(TokenKey) forKey:@"accessToken"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
- [sendParm setValue:valueDic forKey:@"content"];
- [self postMessage:sendParm];
- }
-
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"openAccompanyWebView"]) {
- PREMISSIONTYPE micEnable = [RecordCheckManager checkPermissionShowAlert:NO showInView:nil];
- PREMISSIONTYPE cameraEnable = [RecordCheckManager checkCameraPremissionAvaiable:NO showInView:nil];
- if (micEnable == PREMISSIONTYPE_YES && cameraEnable == PREMISSIONTYPE_YES) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
- KSAccompanyWebViewController *detailCtrl = [[KSAccompanyWebViewController alloc] init];
- detailCtrl.url = [valueDic stringValueForKey:@"url"];
- detailCtrl.parmDic = valueDic;
- detailCtrl.hiddenNavBar = [valueDic boolValueForKey:@"isHideTitle"];
- NSInteger orientation = [valueDic integerValueForKey:@"orientation"];
- BOOL isLandScape = orientation == 0 ? YES : NO;
- if (isLandScape == self.landScape) {
- self.keepOrientation = YES;
- detailCtrl.keepOrientation = YES;
- }
- [self postMessage:parm];
- [self.navigationController pushViewController:detailCtrl animated:YES];
- }
- else {
- if (micEnable == PREMISSIONTYPE_NO && cameraEnable == PREMISSIONTYPE_NO) {
- [self showAlertWithMessage:@"请开启相机和麦克风访问权限" type:CHECKDEVICETYPE_BOTH];
- }
- else if (micEnable == PREMISSIONTYPE_NO) {
- [self showAlertWithMessage:@"请开启麦克风访问权限" type:CHECKDEVICETYPE_MIC];
- }
- else if (cameraEnable == PREMISSIONTYPE_NO) {
- [self showAlertWithMessage:@"请开启相机访问权限" type:CHECKDEVICETYPE_CAMREA];
- }
- }
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"checkAlbum"]) {
- [self postMessage:parm];
- PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable:NO showInView:nil];
- if (albumEnable == PREMISSIONTYPE_NO) {
- [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
- }
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"shareAchievements"]) {
-
- [self shareFunctionWithParm:parm];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"getNavHeight"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
- [valueDic setValue:[NSNumber numberWithFloat:STATUS_GAP*2] forKey:@"navHeight"];
- [valueDic setValue:@(44*2) forKey:@"titleHeight"];
- [parm setValue:valueDic forKey:@"content"];
- [self postMessage:parm];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"backIconChange"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
- NSString *backColor = [valueDic stringValueForKey:@"iconStyle"];
- NSString *backImage = @"";
- if ([backColor isEqualToString:@"black"]) {
- backImage = @"back_black";
- }
- else {
- backImage = @"back_button_white";
- }
- [self.webBackButton.backButton setImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"setBarStatus"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
- BOOL isShow = [valueDic boolValueForKey:@"status"];
- self.hiddenNavBar = !isShow;
- CGFloat navHeight = isShow ? kNaviBarHeight : 0;
- [self.navView mas_updateConstraints:^(MASConstraintMaker *make) {
- make.height.mas_equalTo(navHeight);
- }];
-
- [self.myWebView mas_updateConstraints:^(MASConstraintMaker *make) {
- make.top.mas_equalTo(self.view.mas_top).offset(navHeight);
- }];
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"paymentOrder"]) {
- NSDictionary *content = [parm dictionaryValueForKey:@"content"];
- NSString *channel = [content stringValueForKey:@"payChannel"];
- if ([channel isEqualToString:@"alipay"]) {
- NSString *infoMessage = [content stringValueForKey:@"payInfo"];
- [KSOrderManager dealWithAliSDK:infoMessage];
- }
- else if ([channel isEqualToString:@"wx_lite"]) {
-
- }
-
-
- }
- else if ([[parm stringValueForKey:@"api"] isEqualToString:@"joinChatGroup"]) {
- NSDictionary *valueDic = [parm dictionaryValueForKey:@"content"];
- NSString *targetId = [valueDic stringValueForKey:@"id"];
- if ([valueDic stringValueForKey:@"single"]) {
-
- KSChatConversationViewController *ctrl = [[KSChatConversationViewController alloc] init];
- ctrl.targetId = targetId;
- ctrl.conversationType = ConversationType_PRIVATE;
- [self.navigationController pushViewController:ctrl animated:YES];
-
- }
- else if ([valueDic stringValueForKey:@"multi"]) {
- KSChatConversationViewController *ctrl = [[KSChatConversationViewController alloc] init];
- ctrl.targetId = targetId;
- ctrl.conversationType = ConversationType_GROUP;
- [self.navigationController pushViewController:ctrl animated:YES];
- }
- }
- }
- - (UIImage *)imageWithBase64String:(NSString *)base64String {
- NSURL *URL = [NSURL URLWithString:base64String];
- NSData *imageData = [NSData dataWithContentsOfURL:URL];
- UIImage *image = [UIImage imageWithData:imageData scale:2];
- return image;
- }
- - (void)shareFunctionWithParm:(NSDictionary *)parm {
-
- }
- - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
- [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
-
- } confirm:^{
- [self openSettingView];
- }];
-
- }
- - (void)openSettingView {
- if (@available(iOS 10, *)) {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
- } else {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
- }
- }
- - (void)displaySource:(NSURL *)localUrl {
- KSLocalWebViewController *ctrl = [[KSLocalWebViewController alloc] init];
- ctrl.headTitle = @"协议文件";
- ctrl.sourceData = [NSData dataWithContentsOfURL:localUrl];
- ctrl.fileUrl = localUrl;
- [self.navigationController pushViewController:ctrl animated:YES];
- }
- - (void)postMessage:(NSDictionary *)parm {
- if (_myWebView) {
- dispatch_async(dispatch_get_main_queue(), ^{
- NSString *jsString = [parm mj_JSONString];
- [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"postMessage(%@,'*')", jsString] completionHandler:nil];
- });
- }
- }
- - (void)refreshUrl:(NSString *)refreshUrl {
-
- NSString *sepectString = [refreshUrl containsString:@"?"] ? @"&" : @"?";
- NSString *tokenStr = UserDefault(TokenKey);
- if (![NSString isEmptyString:tokenStr]) {
- NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- refreshUrl = [NSString stringWithFormat:@"%@%@%@",refreshUrl, sepectString, token];
- }
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:refreshUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
- [self.myWebView loadRequest:request];
- }
- - (void)backLoginView {
- [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
- [RCConnectionManager shareManager].isNeedJoin = NO;
- [RCConnectionManager shareManager].isNeedShowMessage = NO;
- [[RCIM sharedRCIM] logout];
-
- NSString *webUrl = [self.url copy];
- if ([webUrl containsString:@"Authorization="]) {
- NSRange range = [webUrl rangeOfString:@"Authorization="];
- if (range.location != NSNotFound) {
- webUrl = [webUrl substringToIndex:range.location-1];
- }
- }
-
-
- NSString *failCount = UserDefault(@"WEB_FAILCOUNT");
- if ([NSString isEmptyString:failCount]) {
- failCount = @"1";
- UserDefaultSetObjectForKey(failCount, @"WEB_FAILCOUNT");
- UserDefaultSetObjectForKey(webUrl, WEB_URL);
- }
- else if (failCount.integerValue == 1) {
-
- NSString *preUrl = UserDefaultObjectForKey(FAIL_WEB_URL);
- if (![webUrl isEqualToString:preUrl]) {
- UserDefaultSetObjectForKey(@"1", @"WEB_FAILCOUNT");
- UserDefaultSetObjectForKey(webUrl, WEB_URL);
- }
- else {
- UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
- }
- }
- else {
- UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
- }
-
- UserDefaultSetObjectForKey(webUrl, FAIL_WEB_URL);
-
-
- [JPUSHService deleteAlias:nil seq:0];
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:TokenKey];
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:Token_type];
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:RongTokenKey];
- [[NSUserDefaults standardUserDefaults] removeObjectForKey:RefreshToken];
- [KSNetworkingManager clearRequestHeader];
- LoginViewController *loginVC = [[LoginViewController alloc] init];
- CustomNavViewController *navCtrl = [[CustomNavViewController alloc] initWithRootViewController:loginVC];
- AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
- appDelegate.window.rootViewController = navCtrl;
-
- }
-
- #pragma mark ----- WKWebView delegate
- - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
- NSLog(@"1-------在发送请求之前,决定是否跳转 -->%@",navigationAction.request);
- NSURL *url = navigationAction.request.URL;
- NSString *scheme = [url scheme];
- UIApplication *app = [UIApplication sharedApplication];
- NSString *urlString = url.absoluteString;
- if (![urlString containsString:@"colexiu.com"] && ![urlString containsString:WEBHOST]) {
- self.isOutLink = YES;
- }
- else {
- self.isOutLink = NO;
- }
-
- if ([scheme isEqualToString:@"tel"]) {
- if ([app canOpenURL:url]) {
- [app openURL:url];
-
- decisionHandler(WKNavigationActionPolicyCancel);
- return;
- }
- }
-
- decisionHandler(WKNavigationActionPolicyAllow);
- }
- - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
- NSLog(@"2-------页面开始加载时调用");
- }
- - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
-
- NSLog(@"3-------在收到响应后,决定是否跳转");
- decisionHandler(WKNavigationResponsePolicyAllow);
- }
- - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
- NSLog(@"4-------当内容开始返回时调用");
- }
- - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
- NSLog(@"5-------页面加载完成之后调用");
- if (_hasModify == NO) {
- [self configLocalStorage];
- }
- }
- - (void)postMessageJS:(NSDictionary *)jsDict {
- NSString *jsString = [jsDict mj_JSONString];
- [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"sendMessage(%@)", jsString] completionHandler:nil];
- }
- - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
- NSLog(@"6-------页面加载失败时调用");
- }
- - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
- NSLog(@"-------接收到服务器跳转请求之后调用");
- }
- - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
- NSLog(@"----数据加载发生错误时调用");
- }
- - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
- {
- if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
- if (challenge.previousFailureCount == 0) {
- NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
- completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
- } else {
- completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
- }
- }
- }
- - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
- NSLog(@"%s", __func__);
- [webView reload];
- }
- - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
- NSLog(@"-------web界面中有弹出警告框时调用");
- NSLog(@"%@",message);
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
- message:nil
- preferredStyle:UIAlertControllerStyleAlert];
- [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
- style:UIAlertActionStyleCancel
- handler:^(UIAlertAction *action) {
- completionHandler();
- }]];
-
- [self presentViewController:alertController animated:YES completion:nil];
- }
- - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
-
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
- message:nil
- preferredStyle:UIAlertControllerStyleAlert];
- [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
- style:UIAlertActionStyleDefault
- handler:^(UIAlertAction *action) {
- completionHandler(YES);
- }]];
- [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
- style:UIAlertActionStyleCancel
- handler:^(UIAlertAction *action){
- completionHandler(NO);
- }]];
-
- [self presentViewController:alertController animated:YES completion:^{}];
-
- }
- #pragma mark - KVO回馈
- -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
- if ([keyPath isEqualToString:@"estimatedProgress"]) {
- self.progressLayer.opacity = 1;
- if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
- return;
- }
- self.progressLayer.frame = CGRectMake(0, 0, kScreenWidth*[change[@"new"] floatValue], 3);
- if ([change[@"new"]floatValue] == 1.0) {
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- self.progressLayer.opacity = 0;
- self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
- });
- }
- }else if ([keyPath isEqualToString:@"title"]) {
-
- self.headTitle = change[@"new"];
- if (self.hiddenNavBar == NO) {
- self.navView.topTitleLabel.text = self.headTitle;
- }
- }
- }
- - (void)configLocalStorage {
- _hasModify = YES;
- if (![NSString isEmptyString:UserDefault(TokenKey)]) {
- NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('Authorization', '%@ %@')",UserDefault(Token_type), UserDefault(TokenKey)];
- [self.myWebView evaluateJavaScript:jsString completionHandler:nil];
- }
- }
- - (void)setupProgress {
- UIView *progress = [[UIView alloc]init];
- progress.frame = CGRectMake(0, 0, kScreenWidth, 3);
- progress.backgroundColor = [UIColor clearColor];
- [self.view addSubview:progress];
-
- CALayer *layer = [CALayer layer];
- layer.frame = CGRectMake(0, 0, 0, 3);
- layer.backgroundColor = THEMECOLOR.CGColor;
- [progress.layer addSublayer:layer];
- self.progressLayer = layer;
- }
- + (WKProcessPool*)singleWkProcessPool {
- static WKProcessPool *sharedPool;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- sharedPool = [[WKProcessPool alloc] init];
- });
- return sharedPool;
- }
- - (NSDictionary *)convertJsonStringToNSDictionary:(NSString *)jsonString {
- if (jsonString == nil) {
- return nil;
- }
- NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
- NSError *error;
- NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
- if (error) {
- NSLog(@"jsonString解析失败:%@", error);
- return nil;
- }
- return json;
- }
- - (void)setHiddenNavBar:(BOOL)hiddenNavBar {
- _hiddenNavBar = hiddenNavBar;
- if (hiddenNavBar) {
- self.navView.topTitleLabel.text = @"";
- }
- else {
- self.navView.topTitleLabel.text = self.headTitle;
- }
- }
- #pragma mark --- lazying
- - (KSWebNavView *)navView {
- if (!_navView) {
- _navView = [[KSWebNavView alloc] init];
-
- }
- return _navView;
- }
- - (KSWebBackButton *)webBackButton {
- if (!_webBackButton) {
- _webBackButton = [[KSWebBackButton alloc] init];
- MJWeakSelf;
- [_webBackButton webViewBackAction:^{
- [weakSelf backAction];
- }];
- }
- return _webBackButton;
- }
- - (void)dealloc {
- [[_myWebView configuration].userContentController removeScriptMessageHandlerForName:@"COLEXIU"];
- [_myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
- [_myWebView removeObserver:self forKeyPath:@"title"];
- [_myWebView loadHTMLString:@"" baseURL:nil];
- [_myWebView removeFromSuperview];
- _myWebView = nil;
- [[NSURLCache sharedURLCache] removeAllCachedResponses];
- [[NSURLCache sharedURLCache] setDiskCapacity:0];
- [[NSURLCache sharedURLCache] setMemoryCapacity:0];
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
- - (NSString *)getSaveSpeedPath {
-
- NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioSpeedFile"];
- NSLog(@"%@",path);
-
- NSFileManager *fileManager = [NSFileManager defaultManager];
- BOOL isDir = FALSE;
- BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
- if(!(isDirExist && isDir)) {
- BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
- if(!bCreateDir){
- NSLog(@"创建文件夹失败!");
- }
- NSLog(@"创建文件夹成功,文件路径%@",path);
- }
-
- path = [path stringByAppendingPathComponent:@"songSpeed.plist"];
- NSLog(@"file path:%@",path);
- return path;
- }
- @end
|