WKWebView的了解
1. http://blog.csdn.net/chenyong05314/article/details/53735215
2. http://www.jianshu.com/p/6ba2507445e4
js的代码如下:
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, maximum-scale=2, minimum-scale=1, user-scalable=no"> <title>首页</title> <style type="text/css"> *{ margin:0; padding: 0; } body,html{ height: 100%; width: 100%; } section{ height: 100%; width: 100%; text-align:center; } .div{ float: left; position: relative; left: 50%; top: 30%; margin-left: -113px; margin-top: -20px; } </style> <script> // $解析器 function $ (ele) { return document.querySelector(ele); }; // 点击确定按钮 function onClickButton() { // 复杂数据 var list = [1,2,3]; var dict = {"name":"阳君", "qq":"937447974", "data":input.value, "list":list}; alert(dict); // JS通知WKWebView //window.webkit.messageHandlers.jsCallOC.postMessage(dict); 注意:内容不能未空 //服务器的格式:window.webkit.messageHandlers.名字.postMessage(内容); window.webkit.messageHandlers.WXPay.postMessage("111111"); window.webkit.messageHandlers.WXPayzhuzhu.postMessage(dict); window.webkit.messageHandlers.DictionaryFunTest111.postMessage("3333"); } function onClickButtonZhuZHuTest() { // 复杂数据 var list = [1,2,3]; var dict = {"name":"阳君", "qq":"937447974", "data":input.value, "list":list}; alert(dict); window.webkit.messageHandlers.WXPay.postMessage("111111"); window.webkit.messageHandlers.WXPayzhuzhu.postMessage(dict); window.webkit.messageHandlers.DictionaryFunTest111.postMessage("3333"); } function DictionaryFunTest() { alert("hahaha"); window.webkit.messageHandlers.WXPay.postMessage("111111"); window.webkit.messageHandlers.DictionaryFunTest111.postMessage("3333"); } // WKWebView调用JS function ocCallJS(params) { show.innerHTML = "111111122222"; alert("55555555"); } function zhuzhuCallTest() { alert("55555"); } // alert对话框 function ale1() { alert("这是一个警告对话框!"); } // confirm选择框 function firm() { if(confirm("去百度看看?")) { alert("你选择了去!"); } else { alert("你选择了不去!"); } } // prompt输入框 function prom() { var result = prompt("演示一个带输入的对话框", "这里输入你的信息"); if(result) { alert("谢谢使用,你输入的是:" + result) } } //调用格式: post('URL', {"key": "value"}); function post(path) { alert("谢谢使用,你输入的是:" ); var method = "post"; var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); } function postZhuDicTest(params) { alert("测试成功"); } </script> </head> <body > <section> <div class="div"> <input type="text" id="input" style="width:150px;line-height:30px"> <a style="margin-left:10px;width:50px;line-height:30px;display:inline-block;background-color:blue;color:#fff;text-align:center;" id="button11" >确定</a> <br> <span id="show" style="display:inline-block;width:100%;text-align:left;font-size:18px;font-family:'微软雅黑';color:#000;margin-top:20px;" ></span> <br><br> <input type="submit" value="警告框" onclick="ale1()" /> <input type="submit" value="选择框" style="margin-left:20px;" onclick="firm()" /> <input type="submit" value="输入框" style="margin-left:20px;" onclick="prom()" /> <a style="margin-left:10px;width:50px;line-height:30px;display:inline-block;background-color:blue;color:#fff;text-align:center;" id="button22" >从OC返回字典</a> </div> </section> <script type="text/javascript"> // 界面渲染完毕执行 var input = $('#input'), button = $('#button11'), show = $('#show'); // 按钮监听 button.addEventListener('click', onClickButton); button22 = $('#button22'), button22.addEventListener('click',onClickButtonZhuZHuTest ) </script> </body> </html>
oc中实现WKWebView的代码如下:
// // WKWebViewController.m // WKWebViewOC // // Created by XiaoFeng on 2016/11/24. // Copyright © 2016年 XiaoFeng. All rights reserved. // QQ群: 384089763 欢迎加入 // github链接: https://github.com/XFIOSXiaoFeng/WKWebView /** 参照一下的1-9个步骤就差不多了 */ #import "WKWebViewController.h" #import <WebKit/WKWebView.h> #import <WebKit/WebKit.h> #import <JavaScriptCore/JavaScriptCore.h> typedef enum{ loadWebURLString = 0, loadWebHTMLString, POSTWebURLString, }wkWebLoadType; static void *WkwebBrowserContext = &WkwebBrowserContext; @interface WKWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UINavigationControllerDelegate,UINavigationBarDelegate> @property (nonatomic, strong) WKWebView *wkWebView; //设置加载进度条 @property (nonatomic,strong) UIProgressView *progressView; //仅当第一次的时候加载本地JS @property(nonatomic,assign) BOOL needLoadJSPOST; //网页加载的类型 @property(nonatomic,assign) wkWebLoadType loadType; //保存的网址链接 @property (nonatomic, copy) NSString *URLString; //保存POST请求体 @property (nonatomic, copy) NSString *postData; //保存请求链接 @property (nonatomic)NSMutableArray* snapShotsArray; //返回按钮 @property (nonatomic)UIBarButtonItem* customBackBarItem; //关闭按钮 @property (nonatomic)UIBarButtonItem* closeButtonItem; @end @implementation WKWebViewController - (void)viewDidLoad { [super viewDidLoad]; //加载web页面 [self webViewloadURLType]; //添加到主控制器上 [self.view addSubview:self.wkWebView]; //添加进度条 [self.view addSubview:self.progressView]; //添加右边刷新按钮 UIBarButtonItem *roadLoad = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(roadLoadClicked)]; self.navigationItem.rightBarButtonItem = roadLoad; } - (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; if (_isNavHidden == YES) { self.navigationController.navigationBarHidden = YES; //创建一个高20的假状态栏 UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)]; //设置成绿色 statusBarView.backgroundColor=[UIColor whiteColor]; // 添加到 navigationBar 上 [self.view addSubview:statusBarView]; }else{ self.navigationController.navigationBarHidden = NO; } } - (void)roadLoadClicked{ [self.wkWebView reload]; } -(void)customBackItemClicked{ if (self.wkWebView.goBack) { [self.wkWebView goBack]; }else{ [self.navigationController popViewControllerAnimated:YES]; } } -(void)closeItemClicked{ [self.navigationController popViewControllerAnimated:YES]; } #pragma mark ================ 懒加载 ================ - (WKWebView *)wkWebView{ if (!_wkWebView) { #pragma mark - 1.初始化并配置 webview //设置网页的配置文件 WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init]; //允许视频播放 Configuration.allowsAirPlayForMediaPlayback = YES; // 允许在线播放 Configuration.allowsInlineMediaPlayback = YES; // 允许可以与网页交互,选择视图 Configuration.selectionGranularity = YES; // web内容处理池 Configuration.processPool = [[WKProcessPool alloc] init]; #pragma mark - 2.自定义配置,便于js调用oc的方法;注意:oc与js的交互,有个js与oc的回调,就添加几个消息处理 //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作) WKUserContentController * UserContentController = [[WKUserContentController alloc]init]; // 添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除 [UserContentController addScriptMessageHandler:self name:@"WXPay"]; [UserContentController addScriptMessageHandler:self name:@"WXPayzhuzhu"]; [UserContentController addScriptMessageHandler:self name:@"DictionaryFunTest111"]; // 是否支持记忆读取 Configuration.suppressesIncrementalRendering = YES; // 允许用户更改网页的设置 Configuration.userContentController = UserContentController; _wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:Configuration]; _wkWebView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]; #pragma mark - 3.设置代理:navigation代理和UIdelegate的代理 // 设置代理 _wkWebView.navigationDelegate = self; _wkWebView.UIDelegate = self; #pragma mark - 添加kvo监听:可添加监听的有,title estimatedProgress loding 等等,从wkwebview.h 中查看 //kvo 添加进度监控 [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkwebBrowserContext]; //开启手势触摸 _wkWebView.allowsBackForwardNavigationGestures = YES; // 设置 可以前进 和 后退 //适应你设定的尺寸 [_wkWebView sizeToFit]; } return _wkWebView; } -(void)viewWillDisappear:(BOOL)animated{ #pragma mark - 4.注销js添加消息的标识 [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"WXPay"]; [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"WXPayzhuzhu"]; [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"DictionaryFunTest111"]; [self.wkWebView setNavigationDelegate:nil]; [self.wkWebView setUIDelegate:nil]; } #pragma mark ================ WKNavigationDelegate ================ #pragma mark - 5.实现navigationDelegate的代理方法 //这个是网页加载完成,导航的变化 -(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{ /* 主意:这个方法是当网页的内容全部显示(网页内的所有图片必须都正常显示)的时候调用(不是出现的时候就调用),,否则不显示,或则部分显示时这个方法就不调用。 */ // 判断是否需要加载(仅在第一次加载) if (self.needLoadJSPOST) { // 调用使用JS发送POST请求的方法 [self postRequestWithJS]; // 将Flag置为NO(后面就不需要加载了) self.needLoadJSPOST = NO; } // 获取加载网页的标题 self.title = self.wkWebView.title; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; [self updateNavigationItems]; } //开始加载 -(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{ //开始加载的时候,让加载进度条显示 self.progressView.hidden = NO; } //内容返回时调用 -(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{} //服务器请求跳转的时候调用 -(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{} //服务器开始请求的时候调用 - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { // NSString* orderInfo = [[AlipaySDK defaultService]fetchOrderInfoFromH5PayUrl:[navigationAction.request.URL absoluteString]]; // if (orderInfo.length > 0) { // [self payWithUrlOrder:orderInfo]; // } // //拨打电话 // //兼容安卓的服务器写法:<a class = "mobile" href = "tel://电话号码"></a> // NSString *mobileUrl = [[navigationAction.request URL] absoluteString]; // mobileUrl = [mobileUrl stringByRemovingPercentEncoding]; // NSArray *urlComps = [mobileUrl componentsSeparatedByString:@"://"]; // if ([urlComps count]){ // // if ([[urlComps objectAtIndex:0] isEqualToString:@"tel"]) { // // UIAlertController *mobileAlert = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"拨号给 %@ ?",urlComps.lastObject] preferredStyle:UIAlertControllerStyleAlert]; // UIAlertAction *suerAction = [UIAlertAction actionWithTitle:@"拨号" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { // // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mobileUrl]]; // }]; // UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { // return ; // }]; // // [mobileAlert addAction:suerAction]; // [mobileAlert addAction:cancelAction]; // // [self presentViewController:mobileAlert animated:YES completion:nil]; // } // } switch (navigationAction.navigationType) { case WKNavigationTypeLinkActivated: { [self pushCurrentSnapshotViewWithRequest:navigationAction.request]; break; } case WKNavigationTypeFormSubmitted: { [self pushCurrentSnapshotViewWithRequest:navigationAction.request]; break; } case WKNavigationTypeBackForward: { break; } case WKNavigationTypeReload: { break; } case WKNavigationTypeFormResubmitted: { break; } case WKNavigationTypeOther: { [self pushCurrentSnapshotViewWithRequest:navigationAction.request]; break; } default: { break; } } [self updateNavigationItems]; decisionHandler(WKNavigationActionPolicyAllow); } // 内容加载失败时候调用 -(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{ NSLog(@"页面加载超时"); } //跳转失败的时候调用 -(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{} //进度条 -(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{} #pragma mark ================ WKUIDelegate ================ #pragma mark - 6.实现uidelegate的代理方法 /** 系统提供了3种提示框,UIDelegate负责与这三个提示框的交互:js的代码 */ // 获取js 里面的提示 --表示js调用了alert提示框 对应的js代码: alert("hahaha"); -(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler(); }]]; [self presentViewController:alert animated:YES completion:NULL]; } // js 信息的交流 /** *对应js的代码如下: if(confirm("去百度看看?")) { alert("你选择了去!"); } else { alert("你选择了不去!"); } */ -(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler(YES); }]]; [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { completionHandler(NO); }]]; [self presentViewController:alert animated:YES completion:NULL]; } // 交互。可输入的文本。 /** * 对应js的代码如下: // prompt输入框 function prom() { var result = prompt("演示一个带输入的对话框", "这里输入你的信息"); if(result) { alert("谢谢使用,你输入的是:" + result) } } */ -(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:prompt preferredStyle:UIAlertControllerStyleAlert]; [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.textColor = [UIColor redColor]; }]; [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler([[alert.textFields lastObject] text]); }]]; [self presentViewController:alert animated:YES completion:NULL]; } #pragma mark ================ WKScriptMessageHandler ================ #pragma mark - 7.实现js调用oc的方法 //拦截执行网页中的JS方法 - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ //服务器固定格式写法 window.webkit.messageHandlers.名字.postMessage(内容); 注意:内容不能为空;名字在步骤2 中已添加了消息处理的配置 //客户端写法 message.name isEqualToString:@"名字"] if ([message.name isEqualToString:@"WXPay"]) { NSLog(@"%@WXPay", message.body); //调用微信支付方法 // [self WXPayWithParam:message.body]; } if ([message.name isEqualToString:@"jsCallOC"]) { NSLog(@"-----点击js的交互jsCallOC-----"); } if ([message.name isEqualToString:@"WXPayzhuzhu"]) { NSLog(@"-----点击js的交互WXPayzhuzhu-----"); } if ([message.name isEqualToString:@"DictionaryFunTest111"]) { NSLog(@"-----点击js的交互DictionaryFun-----"); #pragma mark - 8.实现oc调用js的方法 注意:现在只能实现 输入字符串或者不传参数的交互; 如果需要传字符串的参数的话,如下 NSString *jsStr = [NSString stringWithFormat:@"DictionaryFun('%@');", @"11111"]; /** jsStr 表示调用js的那个方法 NSString *jscriptDic = [NSString stringWithFormat:@"postZhuDicTest('%@')",@"33333333"]; --带字符串参数的 */ NSString *jsStr = [NSString stringWithFormat:@"DictionaryFun();"]; //调用js的DictionnaryFun() 这个方法 [self.wkWebView evaluateJavaScript:jsStr completionHandler:^(id object, NSError * _Nullable error) { NSLog(@"-----postRequestWithJS-----"); }]; } } #pragma mark- 9.kvo的实现 #pragma mark - kvo的设置 //KVO监听进度条 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) { [self.progressView setAlpha:1.0f]; BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress; [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated]; // Once complete, fade out UIProgressView if(self.wkWebView.estimatedProgress >= 1.0f) { [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{ [self.progressView setAlpha:0.0f]; } completion:^(BOOL finished) { [self.progressView setProgress:0.0f animated:NO]; }]; } } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } #pragma mark - 配置界面 -(UIBarButtonItem*)customBackBarItem{ if (!_customBackBarItem) { UIImage* backItemImage = [[UIImage imageNamed:@"backItemImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; UIImage* backItemHlImage = [[UIImage imageNamed:@"backItemImage-hl"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; UIButton* backButton = [[UIButton alloc] init]; [backButton setTitle:@"返回" forState:UIControlStateNormal]; [backButton setTitleColor:self.navigationController.navigationBar.tintColor forState:UIControlStateNormal]; [backButton setTitleColor:[self.navigationController.navigationBar.tintColor colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted]; [backButton.titleLabel setFont:[UIFont systemFontOfSize:17]]; [backButton setImage:backItemImage forState:UIControlStateNormal]; [backButton setImage:backItemHlImage forState:UIControlStateHighlighted]; [backButton sizeToFit]; [backButton addTarget:self action:@selector(customBackItemClicked) forControlEvents:UIControlEventTouchUpInside]; _customBackBarItem = [[UIBarButtonItem alloc] initWithCustomView:backButton]; } return _customBackBarItem; } - (UIProgressView *)progressView{ if (!_progressView) { _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault]; if (_isNavHidden == YES) { _progressView.frame = CGRectMake(0, 20, self.view.bounds.size.width, 3); }else{ _progressView.frame = CGRectMake(0, 64, self.view.bounds.size.width, 3); } // 设置进度条的色彩 [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]]; _progressView.progressTintColor = [UIColor greenColor]; } return _progressView; } -(UIBarButtonItem*)closeButtonItem{ if (!_closeButtonItem) { _closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeItemClicked)]; } return _closeButtonItem; } -(NSMutableArray*)snapShotsArray{ if (!_snapShotsArray) { _snapShotsArray = [NSMutableArray array]; } return _snapShotsArray; } #pragma mark ================ 加载方式 ================ - (void)webViewloadURLType{ self.needLoadJSPOST = YES; //POST使用预先加载本地JS方法的html实现,请确认WKJSPOST存在 [self loadHostPathURL:@"WKJSPOST"]; // switch (self.loadType) { // case loadWebURLString:{ // //创建一个NSURLRequest 的对象 // NSURLRequest * Request_zsj = [NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; // //加载网页 // [self.wkWebView loadRequest:Request_zsj]; // break; // } // case loadWebHTMLString:{ // [self loadHostPathURL:self.URLString]; // break; // } // case POSTWebURLString:{ // // JS发送POST的Flag,为真的时候会调用JS的POST方法 // self.needLoadJSPOST = YES; // //POST使用预先加载本地JS方法的html实现,请确认WKJSPOST存在 // [self loadHostPathURL:@"WKJSPOST"]; // break; // } // } } - (void)loadHostPathURL:(NSString *)url{ //获取JS所在的路径 NSString *path = [[NSBundle mainBundle] pathForResource:url ofType:@"html"]; //获得html内容 NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; //加载js [self.wkWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]]; } // 调用JS发送POST请求 - (void)postRequestWithJS { // 拼装成调用JavaScript的字符串 // NSString *jscript = [NSString stringWithFormat:@"post('%@',{%@});", self.URLString, @{@"key":@"value"}]; NSString *jscript = [NSString stringWithFormat:@"post('%@');", self.URLString]; // 调用JS代码 NSDictionary *prams = @{@"key":@"value"}; NSString *jscriptDic = [NSString stringWithFormat:@"postZhuDicTest('%@')",@"33333333"]; NSString *jsStr = @"postZhuTest();"; [self.wkWebView evaluateJavaScript:jscriptDic completionHandler:^(id object, NSError * _Nullable error) { NSLog(@"-----postRequestWithJS-----"); }]; } - (void)loadWebURLSring:(NSString *)string{ self.URLString = string; self.loadType = loadWebURLString; } - (void)loadWebHTMLSring:(NSString *)string{ self.URLString = string; self.loadType = loadWebHTMLString; } - (void)POSTWebURLSring:(NSString *)string postData:(NSString *)postData{ self.URLString = string; self.postData = postData; self.loadType = POSTWebURLString; } //#pragma mark ============== URL pay 开始支付 ============== // //- (void)payWithUrlOrder:(NSString*)urlOrder //{ // if (urlOrder.length > 0) { // __weak XFWkwebView* wself = self; // [[AlipaySDK defaultService] payUrlOrder:urlOrder fromScheme:@"giftcardios" callback:^(NSDictionary* result) { // // 处理支付结果 // NSLog(@"===============%@", result); // // isProcessUrlPay 代表 支付宝已经处理该URL // if ([result[@"isProcessUrlPay"] boolValue]) { // // returnUrl 代表 第三方App需要跳转的成功页URL // NSString* urlStr = result[@"returnUrl"]; // [wself loadWithUrlStr:urlStr]; // } // }]; // } //} // //- (void)WXPayWithParam:(NSDictionary *)WXparam{ // //} ////url支付成功回调地址 //- (void)loadWithUrlStr:(NSString*)urlStr //{ // if (urlStr.length > 0) { // dispatch_async(dispatch_get_main_queue(), ^{ // NSURLRequest *webRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReturnCacheDataElseLoad // timeoutInterval:15]; // [self.wkWebView loadRequest:webRequest]; // }); // } //} #pragma mark ================ 自定义返回/关闭按钮 ================ -(void)updateNavigationItems{ if (self.wkWebView.canGoBack) { UIBarButtonItem *spaceButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; spaceButtonItem.width = -6.5; [self.navigationItem setLeftBarButtonItems:@[spaceButtonItem,self.customBackBarItem,self.closeButtonItem] animated:NO]; }else{ self.navigationController.interactivePopGestureRecognizer.enabled = YES; [self.navigationItem setLeftBarButtonItems:@[self.customBackBarItem]]; } } //请求链接处理 -(void)pushCurrentSnapshotViewWithRequest:(NSURLRequest*)request{ // NSLog(@"push with request %@",request); NSURLRequest* lastRequest = (NSURLRequest*)[[self.snapShotsArray lastObject] objectForKey:@"request"]; //如果url是很奇怪的就不push if ([request.URL.absoluteString isEqualToString:@"about:blank"]) { // NSLog(@"about blank!! return"); return; } //如果url一样就不进行push if ([lastRequest.URL.absoluteString isEqualToString:request.URL.absoluteString]) { return; } UIView* currentSnapShotView = [self.wkWebView snapshotViewAfterScreenUpdates:YES]; [self.snapShotsArray addObject: @{@"request":request,@"snapShotView":currentSnapShotView}]; } //注意,观察的移除 -(void)dealloc{ [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))]; } @end