// // ZCBaseBaseWebView.m // HuaKaiChat // // Created by 张灿 on 2017/6/28. // Copyright © 2017年 huakai. All rights reserved. // #import "ZCBaseWebView.h" #import #import "YOUPAILZUserShowVC.h" #import "YOUPAILZLiveAudienceVC.h" #import "UIViewController+TFPresent.h" //#import "IPAManager.h" //#import "WXApi.h" #import "YOUPAILCIMSessionVC.h" #import "YOUPAILCShareModel.h" #import #import "YOUPAILZShareApplicationWindow.h" #import "IPAManager.h" #import "YOUPAIHRWebWindow.h" @interface ZCBaseWebView() @property (nonatomic,assign) double estimatedProgress; @property (nonatomic,strong) NSURLRequest *originRequest; @property (nonatomic,strong) NSURLRequest *currentRequest; @property (nonatomic,strong) UILabel *tipLabel; @property (nonatomic,strong) UILabel *errorLabel; @property (nonatomic,strong) ZCBaseWebProgressView* ZCBaseWebProgressView; @property (nonatomic,assign)BOOL ResetFlag;//已设置标志 @property (nonatomic,strong) WKWebView* wkwebView; @end @implementation ZCBaseWebView @synthesize realWebView = _realWebView; - (UILabel *)errorLabel{ if (!_errorLabel) { _errorLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, KScreenWidth, 30)]; _errorLabel.text = @"网页加载失败"; _errorLabel.textColor = DecColorFromRGB(110, 115, 116); _errorLabel.font = [UIFont systemFontOfSize:15]; _errorLabel.textAlignment = NSTextAlignmentCenter; [self addSubview:_errorLabel]; } return _errorLabel; } - (UILabel *)tipLabel{ if (!_tipLabel) { _tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, KScreenWidth, 30)]; NSString *endStr; NSRange start = [self.contentUrl rangeOfString:@"//"]; NSString* startStr = [self.contentUrl substringFromIndex:start.location+2]; NSRange end = [startStr rangeOfString:@"/"]; if (end.length==0) { endStr = startStr; }else{ endStr = [startStr substringToIndex:end.location]; } _tipLabel.text = [NSString stringWithFormat:@"网页由 %@ 提供",endStr]; _tipLabel.textColor = DecColorFromRGB(110, 115, 116); _tipLabel.font = [UIFont systemFontOfSize:15]; _tipLabel.textAlignment = NSTextAlignmentCenter; [self.wkwebView addSubview:_tipLabel]; } return _tipLabel; } - (instancetype)init { return [self initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-NavBarHeight)]; } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self _initMyself]; } return self; } - (instancetype)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; if (self) { [self _initMyself]; } return self; } -(void)_initMyself { // self.backgroundColor = DecColorFromRGB(46, 49, 50); self.wkwebView.scrollView.bounces = NO; self.backgroundColor = LCBkgColor; self.ResetFlag = NO; Class wkWebView = NSClassFromString(@"WKWebView"); if(wkWebView) { [self initWKWebView]; } else { } // self.scalesPageToFit = YES; [self.realWebView setFrame:self.bounds]; [self.realWebView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight]; [self addSubview:self.realWebView]; } -(void)initWKWebView { WKUserContentController *userContentController = [[WKUserContentController alloc] init]; [userContentController addScriptMessageHandler:self name:@"openUserDetail"];//js调用跳转至用户详情 [userContentController addScriptMessageHandler:self name:@"openUserLive"];// js调用跳转至直播间 [userContentController addScriptMessageHandler:self name:@"openActivity"]; //js调用可跳转app指定内页 [userContentController addScriptMessageHandler:self name:@"showPay"]; // 支付 // [userContentController addScriptMessageHandler:self name:@"showShareDialog"];// 分享 [userContentController addScriptMessageHandler:self name:@"copyInviteCode"];// 复制到剪切板 [userContentController addScriptMessageHandler:self name:@"showPosterDialog"];// 分享推广 [userContentController addScriptMessageHandler:self name:@"getUserId"];// 把用户id传给H5 [userContentController addScriptMessageHandler:self name:@"startP2PSession"];// 客服 [userContentController addScriptMessageHandler:self name:@"showH5Dialog"]; //js调用Web窗口 [userContentController addScriptMessageHandler:self name:@"closeWindow"]; //关闭界面 [userContentController addScriptMessageHandler:self name:@"showNewShareDialog"]; //第三方分享 [userContentController addScriptMessageHandler:self name:@"openMainActivity"]; //js调用可跳转app指定内页 WKWebViewConfiguration* configuration = [[NSClassFromString(@"WKWebViewConfiguration") alloc] init]; configuration.preferences = [NSClassFromString(@"WKPreferences") new]; configuration.userContentController = userContentController; WKWebView* webView = [[NSClassFromString(@"WKWebView") alloc] initWithFrame:self.bounds configuration:configuration]; webView.UIDelegate = self; webView.navigationDelegate = self; webView.backgroundColor = [UIColor clearColor]; webView.opaque = YES; webView.allowsLinkPreview = NO; webView.allowsBackForwardNavigationGestures = YES; [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; self.wkwebView = webView; _realWebView = webView; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(youpaifApplePaySuccess:) name:@"yqApplePaySuccess" object:nil]; } - (void)youpaifApplePaySuccess:(NSNotification*)noti{ [self.wkwebView evaluateJavaScript:@"callback()" completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"%@", error); }]; [self.wkwebView evaluateJavaScript:@"vue_onload()" completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"%@", error); }]; } //js调oc - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ if ([message.name isEqualToString:@"openUserDetail"]) { //int userId,int type // 用户id NSLog(@"方法名:%@", message.name); NSLog(@"参数:%@", message.body); if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; NSNumber *type = dict[@"type"]; NSNumber *userId = dict[@"userId"]; if ([type isEqualToNumber:@1]) { // YOUPAILZUserShowVC *vc = [YOUPAILZUserShowVC new]; // vc.youpaipuserId = [NSString stringWithFormat:@"%@",userId]; // [self.nav pushViewController:vc animated:YES]; YMPersonalPageViewModel *personalPageVM = [[YMPersonalPageViewModel alloc]initWithParams:@{ ParamsId:@([userId intValue]) }]; [YMRouter openURL:stringFormat(@"%@%@", YM_ROUTER_URL_PREFIX, YM_ROUTER_PERSONAL_PAGE) withUserInfo:@{ RouterViewModel:personalPageVM } completion:nil]; } } }else if ([message.name isEqualToString:@"openUserLive"]){ // String roomId // 直播间id NSLog(@"直播方法名:%@", message.name); NSLog(@"直播参数:%@", message.body); NSNumber *roomId = message.body; [ZCHUDHelper showWithStatus:nil]; WeakSelf; [LCHttpHelper requestWithURLString:JoinLive parameters:@{@"room_id":[NSString stringWithFormat:@"%@",roomId]} needToken:YES type:HttpRequestTypePost success:^(id responseObject) { NSDictionary* dict = (NSDictionary*)responseObject; NSInteger code = [[dict objectForKey:@"code"] integerValue]; if (code == 0) { [ZCHUDHelper dismiss]; [[YOUPAILZChatRoomManager shareManager] youpaifcloseChatRoom]; YOUPAILZLiveModel *liveModel = [YOUPAILZLiveModel mj_objectWithKeyValues:[dict objectForKey:@"data"]]; YOUPAILZLiveAudienceVC *audienceVC = [[YOUPAILZLiveAudienceVC alloc] initWithModel:liveModel]; [weakSelf.nav pushViewController:audienceVC animated:YES]; }else{ [ZCHUDHelper showTitle:[dict objectForKey:@"message"]]; } } failure:^(NSError *error) { [ZCHUDHelper showTitle:error.localizedDescription]; }]; }else if ([message.name isEqualToString:@"openActivity"]){ //int linkType,String linkUrl // NSLog(@"openActivity方法名:%@", message.name); // NSLog(@"openActivity参数:%@", message.body); if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; NSNumber *link_type = dict[@"linkType"]; NSString *link_url = dict[@"linkUrl"]; if ([link_type isEqualToNumber:@1]) { ZCBaseWebVC* baseWeb = [[ZCBaseWebVC alloc]init]; baseWeb.contentUrl = link_url; [self.nav pushViewController:baseWeb animated:YES]; }else if ([link_type isEqualToNumber:@2]||[link_type isEqualToNumber:@3]){ [[LCTools getCurrentVC] youpaifpageToStr:link_url]; } } }else if ([message.name isEqualToString:@"openMainActivity"]){ if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; NSString *type = dict[@"type"]; [[LCTools getCurrentVC] youpaifpageToStr:type]; } }else if ([message.name isEqualToString:@"showPay"]){ if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; NSString *ios_product_id = [NSString stringWithFormat:@"%@",dict[@"ios_product_id"]]; [self applePay:ios_product_id]; } } // else if([message.name isEqualToString:@"showShareDialog"]){ // if ([message.body isKindOfClass:[NSDictionary class]]) { // NSDictionary *dict = message.body; // NSString *imageUrl = [NSString stringWithFormat:@"%@",dict[@"imageUrl"]]; // NSString *weChatUrl = [NSString stringWithFormat:@"%@",dict[@"weChatUrl"]]; // [self shareWithQrcodeUrl:imageUrl Url:weChatUrl]; // } // // } else if([message.name isEqualToString:@"copyInviteCode"]){ if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; NSString *inviteCode = [NSString stringWithFormat:@"%@",dict[@"inviteCode"]]; UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = inviteCode; [ZCHUDHelper showTitle:@"复制成功,快去粘贴吧!"]; } }else if([message.name isEqualToString:@"showPosterDialog"]){ if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; YOUPAILZShareApplicationModel *model = [YOUPAILZShareApplicationModel mj_objectWithKeyValues:dict]; YOUPAILZShareApplicationWindow *vc = [[YOUPAILZShareApplicationWindow alloc] init]; vc.youpaipmodel = model; vc.isTouchDismiss = YES; [[LCTools getCurrentVC] TFPresentVC:vc completion:^{}]; } }else if([message.name isEqualToString:@"getUserId"]){ if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; NSString *methodName = [dict objectForKey:@"fn"]; [self.wkwebView evaluateJavaScript:[NSString stringWithFormat:@"%@('%@')",methodName,[LCSaveModel getUserModel].youpaipuserinfo.youpaipuser_id] completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"%@", error); }]; } }else if([message.name isEqualToString:@"startP2PSession"]){ NIMSession *session = [NIMSession session:[LCSaveData getServerId] type:NIMSessionTypeP2P]; if (session) { @weakify(self); [ZCHUDHelper show]; [[[NIMSDK sharedSDK] userManager] fetchUserInfos:@[session.sessionId] completion:^(NSArray * _Nullable users, NSError * _Nullable error) { @strongify(self); [ZCHUDHelper dismiss]; YOUPAILCIMSessionVC *vc = [[YOUPAILCIMSessionVC alloc] initWithSession:session]; [[LCTools getContainNavigationControllerCurrentVC].navigationController pushViewController:vc animated:YES]; }]; } }else if ([message.name isEqualToString:@"showH5Dialog"]){ //int linkType,String linkUrl // NSLog(@"openActivity方法名:%@", message.name); // NSLog(@"openActivity参数:%@", message.body); if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; NSString *gravity = dict[@"gravity"]; CGFloat width = [dict[@"width"] floatValue]; CGFloat height = [dict[@"height"] floatValue]; NSString *loadUrl = dict[@"loadUrl"]; YOUPAIHRWebWindow *window = [[YOUPAIHRWebWindow alloc] init]; window.youpaipgravity = gravity; window.youpaipwidth = width; window.youpaipheight = height; window.youpaipurl = loadUrl; [[LCTools getCurrentVC] TFPresentVC:window completion:^{}]; } }else if ([message.name isEqualToString:@"closeWindow"]){ [[LCTools getContainNavigationControllerCurrentVC].navigationController popViewControllerAnimated:YES]; }else if([message.name isEqualToString:@"showNewShareDialog"]){ if ([message.body isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = message.body; NSString *title = [NSString stringWithFormat:@"%@",dict[@"title"]]; NSString *linkUrl = [NSString stringWithFormat:@"%@",dict[@"linkUrl"]]; NSString *thumbUrl = [NSString stringWithFormat:@"%@",dict[@"thumbUrl"]]; NSString *des = [NSString stringWithFormat:@"%@",dict[@"des"]]; [self shareWithTitle:title linkUrl:linkUrl thumbUrl:thumbUrl des:des]; } } } - (void)shareWithTitle:(NSString *)title linkUrl:(NSString *)linkUrl thumbUrl:(NSString *)thumbUrl des:(NSString *)des{ ZCShareActionBtn *action1 = [ZCShareActionBtn actionWithTitle:@"微信" image:[UIImage imageNamed:@"vqu_images_share_weixin"] andblock:^(NSString *str) { [self shareWithPlatform:UMSocialPlatformType_WechatSession title:title linkUrl:linkUrl thumbUrl:thumbUrl des:des]; }]; ZCShareActionBtn *action2 = [ZCShareActionBtn actionWithTitle:@"朋友圈" image:[UIImage imageNamed:@"vqu_images_share_weixin_timeline"] andblock:^(NSString *str) { [self shareWithPlatform:UMSocialPlatformType_WechatTimeLine title:title linkUrl:linkUrl thumbUrl:thumbUrl des:des]; }]; // ZCShareActionBtn *action3 = [ZCShareActionBtn actionWithTitle:@"微博" image:[UIImage imageNamed:@"vqu_images_share_weibo"] andblock:^(NSString *str) { // UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; // pasteboard.string = linkUrl; // [ZCHUDHelper showTitle:@"复制成功,快去粘贴吧!"]; // }]; ZCShareActionBtn *action4 = [ZCShareActionBtn actionWithTitle:@"QQ" image:[UIImage imageNamed:@"vqu_images_share_qq"] andblock:^(NSString *str) { [self shareWithPlatform:UMSocialPlatformType_QQ title:title linkUrl:linkUrl thumbUrl:thumbUrl des:des]; }]; ZCShareActionBtn *action5 = [ZCShareActionBtn actionWithTitle:@"QQ空间" image:[UIImage imageNamed:@"vqu_images_share_qzone"] andblock:^(NSString *str) { [self shareWithPlatform:UMSocialPlatformType_Qzone title:title linkUrl:linkUrl thumbUrl:thumbUrl des:des]; }]; @weakify(self); ZCShareActionBtn *action6 = [ZCShareActionBtn actionWithTitle:@"生成图片" image:[UIImage imageNamed:@"vqu_images_share_qrcode"] andblock:^(NSString *str) { @strongify(self); [self.wkwebView evaluateJavaScript:@"notifyPoster()" completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"%@", error); }]; // YOUPAILCMyQRCodeVC* qrcodeVC = [[YOUPAILCMyQRCodeVC alloc]init]; // qrcodeVC.qrcode = qrcodeUrl; // qrcodeVC.url = url; // [[LCTools getCurrentVC].navigationController pushViewController:qrcodeVC animated:YES]; // YOUPAILZShareApplicationWindow *vc = [[YOUPAILZShareApplicationWindow alloc] init]; // vc.isTouchDismiss = YES; // [[LCTools getCurrentVC] TFPresentVC:vc completion:^{}]; }]; ZCShareActionBtn *action7 = [ZCShareActionBtn actionWithTitle:@"复制链接" image:[UIImage imageNamed:@"vqu_images_share_link"] andblock:^(NSString *str) { UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = linkUrl; [ZCHUDHelper showTitle:@"复制成功,快去粘贴吧!"]; }]; ZCShareSheetView* shareView = [[ZCShareSheetView alloc]initWithTitle:@"推荐给好友" andShowCancelButton:YES andAction:@[action6,action1,action2,action4,action5,action7] column:5]; shareView.alertWindow.hidden = NO; [shareView show]; // [LCHttpHelper requestWithURLString:InviteInit parameters:nil needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) { // NSDictionary* dict = (NSDictionary*)responseObject; // NSInteger code = [[dict objectForKey:@"code"] integerValue]; // if (code==0) {//成功 // YOUPAILCShareModel *shareModel = [YOUPAILCShareModel mj_objectWithKeyValues:[[dict objectForKey:@"data"]objectForKey:@"share"]]; // NSString *qrcode = [[dict objectForKey:@"data"]objectForKey:@"qrcode"]; // NSString *url = shareModel.url; // // } // } failure:^(NSError *error) { // // }]; } - (void)shareWithPlatform:(UMSocialPlatformType)platformType title:(NSString *)title linkUrl:(NSString *)linkUrl thumbUrl:(NSString *)thumbUrl des:(NSString *)des{ UMSocialMessageObject* message = [[UMSocialMessageObject alloc]init]; NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:thumbUrl]]; UMShareWebpageObject* webPage = [UMShareWebpageObject shareObjectWithTitle:title descr:des thumImage:imageData]; webPage.webpageUrl = linkUrl; message.shareObject = webPage; @weakify(self); [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:message currentViewController:nil completion:^(id result, NSError *error) { if (error == nil) { [LCHttpHelper requestWithURLString:ShareTask parameters:@{} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) { NSDictionary* dict = (NSDictionary*)responseObject; NSInteger code = [[dict objectForKey:@"code"] integerValue]; if (code==0) {//成功 @strongify(self); [self youpaifApplePaySuccess:nil]; } } failure:^(NSError *error) { }]; } }]; } - (void)applePay:(NSString *)ios_product_id{ // self.buyBtn.userInteractionEnabled = NO; /// 内购 [ZCHUDHelper showWithStatus:@"支付中..."]; NSLog(@"%@",ios_product_id); [[IPAManager shareIAPManager] startPurchWithID:ios_product_id completeHandle:^(IAPPurchType type, NSString *data) { NSLog(@"type = %ld",type); if (type == IAPPurchSuccess) { [LCSaveData saveReceiptData:data]; [self requestApplePayBack:data]; }else{ // dispatch_async(dispatch_get_main_queue(), ^{ // self.buyBtn.userInteractionEnabled = YES; // }); NSString *title = @""; switch (type) { case IAPPurchFailed: title = @"购买失败"; break; case IAPPurchCancle: title = @"已取消购买"; break; case IAPPurchVerFailed: title = @"订单校验失败"; break; // case IAPPurchVerSuccess: // NSLog(@"订单校验成功"); // break; case IAPPurchNotArrow: title = @"不允许程序内付费"; break; default: break; } if (title.length == 0) { [ZCHUDHelper dismiss]; }else{ [ZCHUDHelper showTitle:title]; } } }]; } - (void)requestApplePayBack:(NSString *)receipt_data{ [LCHttpHelper requestWithURLString:ApplePayBack parameters:@{@"receipt_data":receipt_data} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) { NSDictionary* dict = (NSDictionary*)responseObject; NSInteger code = [[dict objectForKey:@"code"] integerValue]; // dispatch_async(dispatch_get_main_queue(), ^{ // self.buyBtn.userInteractionEnabled = YES; // }); if (code == 0) { [LCSaveData removeReceiptData:receipt_data]; NSInteger type = 4; // if (![LCSaveData getOnlineVersion]) { // type = 4; // } // [self initDataWithType:type]; // if (self.paySuccessBlock != nil) { // self.paySuccessBlock(); // } [self.wkwebView evaluateJavaScript:@"callback()" completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"%@", error); }]; } [ZCHUDHelper showTitle:[dict objectForKey:@"message"]]; } failure:^(NSError *error) { // dispatch_async(dispatch_get_main_queue(), ^{ // self.buyBtn.userInteractionEnabled = YES; // }); [ZCHUDHelper showTitle:error.localizedDescription]; }]; } -(void)loadRequest:(NSURLRequest *)request { [(WKWebView*)self.realWebView loadRequest:request]; } - (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL { [(WKWebView*)self.realWebView loadHTMLString:string baseURL:baseURL]; } //计算js代码 - (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString * _Nullable)script { //如果是用wkwebview 来获取title 可以直接使用title属性 if ([script isEqualToString:@"document.title"]) { return ((WKWebView*)self.realWebView).title; }else{ __block NSString *resultString = nil; [(WKWebView*)self.realWebView evaluateJavaScript:script completionHandler:^(id result, NSError *error) { if (error == nil) { if (result != nil) { resultString = [NSString stringWithFormat:@"%@", result]; } } else { NSLog(@"evaluateJavaScript error : %@", error.localizedDescription); } }]; while (resultString == nil) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } return resultString; } } #pragma mark --> WKWebView的代理方法 -(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { BOOL resultBOOL = YES; BOOL isLoadingDisableScheme = [self isLoadingWKWebViewDisableScheme:navigationAction.request.URL]; if(resultBOOL && !isLoadingDisableScheme) { self.currentRequest = navigationAction.request; if(navigationAction.targetFrame == nil) { [webView loadRequest:navigationAction.request]; } decisionHandler(WKNavigationActionPolicyAllow); } else { decisionHandler(WKNavigationActionPolicyCancel); } } -(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { } -(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { [self callback_webViewDidFinishLoad]; } - (void)webView:(WKWebView *) webView didFailProvisionalNavigation: (WKNavigation *) navigation withError: (NSError *) error { [self callback_webViewDidFailLoadWithError:error]; } - (void)webView: (WKWebView *)webView didFailNavigation:(WKNavigation *) navigation withError: (NSError *) error { [self callback_webViewDidFailLoadWithError:error]; } #pragma mark- CALLBACK IMYVKWebView Delegate - (void)callback_webViewDidFinishLoad { if([self.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { [self.delegate webViewDidFinishLoad:self]; } if (!self.ResetFlag) { self.scrollView.backgroundColor = [UIColor clearColor]; [self.wkwebView insertSubview:self.tipLabel belowSubview:self.wkwebView.scrollView]; self.ResetFlag = YES; } } - (void)callback_webViewDidFailLoadWithError:(NSError *)error { if([self.delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) { [self.delegate webView:self didFailLoadWithError:error]; } [self insertSubview:self.errorLabel belowSubview:self.realWebView]; } -(BOOL)callback_webViewShouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(NSInteger)navigationType { BOOL resultBOOL = YES; if([self.delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) { if(navigationType == -1) { navigationType = 5; } resultBOOL = YES; } return resultBOOL; } -(UIScrollView *)scrollView { return [(id)self.realWebView scrollView]; } #pragma mark- 基础方法 #pragma mark- 如果没有找到方法 去realWebView 中调用 -(BOOL)respondsToSelector:(SEL)aSelector { BOOL hasResponds = [super respondsToSelector:aSelector]; if(hasResponds == NO) { hasResponds = [self.delegate respondsToSelector:aSelector]; } if(hasResponds == NO) { hasResponds = [self.realWebView respondsToSelector:aSelector]; } return hasResponds; } ///判断当前加载的url是否是WKWebView不能打开的协议类型 - (BOOL)isLoadingWKWebViewDisableScheme:(NSURL *)url { BOOL retValue = NO; //判断是否正在加载WKWebview不能识别的协议类型:phone numbers, email address, maps, etc. if([url.scheme isEqualToString:@"tel"]) { UIApplication *app = [UIApplication sharedApplication]; if ([app canOpenURL:url]) { [app openURL:url]; retValue = YES; } } return retValue; } //WkWebView的progress 回调 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([keyPath isEqualToString:@"estimatedProgress"]) { self.estimatedProgress = [change[NSKeyValueChangeNewKey] doubleValue]; [self callback_webViewUpdateProgress:self.estimatedProgress]; } else if([keyPath isEqualToString:@"title"]) { self.title = change[NSKeyValueChangeNewKey]; if([self.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { [self.delegate webViewDidFinishLoad:self]; } } } //uiwebview的progress njk progress的代理方法 -(void)webViewProgress:(ZCBaseWebProgressView *)webViewProgress updateProgress:(float)progress { self.estimatedProgress = progress; [self callback_webViewUpdateProgress:progress]; } - (void)callback_webViewUpdateProgress:(float)progress { if([self.delegate respondsToSelector:@selector(webView:updateProgress:)]) { [self.delegate webView:self updateProgress:progress]; } } #pragma mark- 清理 -(void)dealloc { WKWebView* webView = _realWebView; webView.UIDelegate = nil; webView.navigationDelegate = nil; [webView removeObserver:self forKeyPath:@"estimatedProgress"]; [webView removeObserver:self forKeyPath:@"title"]; [_realWebView scrollView].delegate = nil; [_realWebView stopLoading]; [_realWebView removeFromSuperview]; _realWebView = nil; [[NSNotificationCenter defaultCenter] removeObserver:self]; } @end #pragma mark - ZCBaseWebProgressView NSString *completeRPCURLPath = @"/ZCBaseWebProgressViewproxy/complete"; const float NJKInitialProgressValue = 0.1f; const float NJKInteractiveProgressValue = 0.5f; const float NJKFinalProgressValue = 0.9f; @implementation ZCBaseWebProgressView { NSUInteger _loadingCount; NSUInteger _maxLoadCount; NSURL *_currentURL; BOOL _interactive; } - (id)init { self = [super init]; if (self) { _maxLoadCount = _loadingCount = 0; _interactive = NO; } return self; } - (void)startProgress { if (_progress < NJKInitialProgressValue) { [self setProgress:NJKInitialProgressValue]; } } - (void)incrementProgress { float progress = self.progress; float maxProgress = _interactive ? NJKFinalProgressValue : NJKInteractiveProgressValue; float remainPercent = (float)_loadingCount / (float)_maxLoadCount; float increment = (maxProgress - progress) * remainPercent; progress += increment; progress = fmin(progress, maxProgress); [self setProgress:progress]; } - (void)completeProgress { [self setProgress:1.0]; } - (void)setProgress:(float)progress { // progress should be incremental only if (progress > _progress || progress == 0) { _progress = progress; if ([_progressDelegate respondsToSelector:@selector(webViewProgress:updateProgress:)]) { [_progressDelegate webViewProgress:self updateProgress:progress]; } if (_progressBlock) { _progressBlock(progress); } } } - (void)reset { _maxLoadCount = _loadingCount = 0; _interactive = NO; [self setProgress:0.0]; } @end