2.WKWebView的使用(大坑:网址没加http://)
2.1加载一个WKWebView,进度View以及基本配置
- (void)loadWebView{
//初始化一个WKWebViewConfiguration对象
WKWebViewConfiguration*config = [[WKWebViewConfigurationalloc]init];
//初始化偏好设置:
config.preferences= [[WKPreferencesalloc]init];
//设置最小字体默认是0
config.preferences.minimumFontSize=10;
//是否支持JavaScript
config.preferences.javaScriptEnabled=YES;
//不通过用户交互,是否可以打开窗口
config.preferences.javaScriptCanOpenWindowsAutomatically=NO;
//创建WKWebView,并且配置webView
self.webView= [[WKWebViewalloc]initWithFrame:self.view.boundsconfiguration:config];
[self.viewaddSubview:self.webView];
//1.加载网页
NSURL*url = [NSURLURLWithString:@"http://www.baidu.com"];
NSURLRequest*request = [[NSURLRequestalloc]initWithURL:url];
[webViewloadRequest:request];
//2.或者加载本地的测试网页
NSURL*path = [[NSBundlemainBundle]URLForResource:@"WKWebViewText"withExtension:@"html"];
NSURLRequest*request = [NSURLRequestrequestWithURL:path];
[webViewloadRequest:request];
//加载完之后要设置代理
self.webView.UIDelegate=self;
self.webView.navigationDelegate=self;
}
- (void)loadProgressView{
CGRectframe;
frame.size=self.view.bounds.size;
frame.origin.x=self.view.bounds.origin.x;
frame.origin.y=65;
self.progressView= [[UIProgressViewalloc]initWithFrame:frame];
self.progressView.backgroundColor= [UIColorredColor];
[self.viewaddSubview:self.progressView];
}
2.2WKWebView的添加监听,移除监听
- (void)addObserver{
[self.webViewaddObserver:selfforKeyPath:@"loading"options:NSKeyValueObservingOptionNewcontext:nil];
[self.webViewaddObserver:selfforKeyPath:@"title"options:NSKeyValueObservingOptionNewcontext:nil];
[self.webViewaddObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNewcontext:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[superviewWillDisappear:animated];
//移除监听
[self.webViewremoveObserver:selfforKeyPath:@"loading"];
[self.webViewremoveObserver:selfforKeyPath:@"title"];
[self.webViewremoveObserver:selfforKeyPath:@"estimatedProgress"];
}
//KVO监听函数
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void*)context {
if([keyPathisEqualToString:@"title"]) {
self.title=self.webView.title;
}elseif([keyPathisEqualToString:@"loading"]){
NSLog(@"loading");
}elseif([keyPathisEqualToString:@"estimatedProgress"]) {
self.progressView.progress=self.webView.estimatedProgress;
}
if(!self.webView.loading) {
[UIViewanimateWithDuration:0.5animations:^{
self.progressView.alpha=0;
}];
}
}
设置导航栏
- (void)addNavigationBarButton{
self.navigationItem.leftBarButtonItem= [[UIBarButtonItemalloc]initWithTitle:@"后退"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(goBack)];
self.navigationItem.rightBarButtonItem= [[UIBarButtonItemalloc]initWithTitle:@"前进"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(goForward)];
}
- (void)goBack {
if([self.webViewcanGoBack]) {
[self.webViewgoBack];
NSLog(@"后退");
}
}
- (void)goForward {
if([self.webViewcanGoForward]) {
[self.webViewgoForward];
NSLog(@"前进");
}
}
2.3WKWebView的代理方法
#pragma mark -代理方法
//WKScriptMessageHandler的代理方法
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message{
//这里可以通过name处理多组交互通过senderModel,来区别信号
if([message.nameisEqualToString:@"senderModel"]) {
//body只支持NSNumber, NSString, NSDate, NSArray,NSDictionary和NSNull类型
NSLog(@"%@",message.body);
}
}
#pragma mark - WKNavigationDelegate
//在发送请求之前,决定是否跳转
- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler {
NSString*hostName = navigationAction.request.URL.host.lowercaseString;
NSLog(@"%@",hostName);
if(navigationAction.navigationType==WKNavigationTypeLinkActivated&& ![hostNamecontainsString:@".baidu.com"]) {
//手动跳转
[[UIApplicationsharedApplication]openURL:navigationAction.request.URL];
//不允许webView内跳转
decisionHandler(WKNavigationActionPolicyCancel);
}else{
self.progressView.alpha=1.0;
decisionHandler(WKNavigationActionPolicyAllow);
}
}
//在响应完成时,调用的方法.如果设置为不允许响应, web内容就不会传过来
- (void)webView:(WKWebView*)webView decidePolicyForNavigationResponse:(WKNavigationResponse*)navigationResponse decisionHandler:(void(^)(WKNavigationResponsePolicy))decisionHandler {
decisionHandler(WKNavigationResponsePolicyAllow);
}
//接收到服务器跳转请求之后调用
- (void)webView:(WKWebView*)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation*)navigation{
}
//开始加载时调用
- (void)webView:(WKWebView*)webView didStartProvisionalNavigation:(WKNavigation*)navigation{
}
//当内容开始返回时调用
- (void)webView:(WKWebView*)webView didCommitNavigation:(WKNavigation*)navigation{
}
//页面加载完成之后调用
- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation{
NSLog(@"title:%@",webView.title);
}
//页面加载失败时调用
- (void)webView:(WKWebView*)webView didFailProvisionalNavigation:(WKNavigation*)navigation
{
}
#pragma mark - WKUIDelegate
//alert警告框
- (void)webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(void))completionHandler {
UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"警告"message:@"调用警告框"preferredStyle:UIAlertControllerStyleAlert];
[alertaddAction:[UIAlertActionactionWithTitle:@"OK"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
completionHandler();
}]];
[selfpresentViewController:alertanimated:YEScompletion:nil];
NSLog(@"alert message:%@",message);
}
//confirm确认框
- (void)webView:(WKWebView*)webView runJavaScriptConfirmPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(BOOL))completionHandler{
UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"确认框"message:@"调用confirm提示框"preferredStyle:UIAlertControllerStyleAlert];
[alertaddAction:[UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
completionHandler(YES);
}]];
[alertaddAction:[UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:^(UIAlertAction*_Nonnullaction) {
completionHandler(NO);
}]];
[selfpresentViewController:alertanimated:YEScompletion:NULL];
NSLog(@"confirm message:%@", message);
}
//输入框
- (void)webView:(WKWebView*)webView runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt defaultText:(NSString*)defaultText initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(NSString*_Nullable))completionHandler {
UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"输入框"message:@"调用输入框"preferredStyle:UIAlertControllerStyleAlert];
[alertaddTextFieldWithConfigurationHandler:^(UITextField*_NonnulltextField) {
textField.textColor= [UIColorblackColor];
}];
[alertaddAction:[UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
completionHandler([alert.textFieldslastObject].text);
}]];
[selfpresentViewController:alertanimated:YEScompletion:nil];
}
2.4WKWebView的对象方法
//加载本地 URL 文件
- (nullableWKNavigation*)loadFileURL:(NSURL*)URL allowingReadAccessToURL:(NSURL*)readAccessURL NS_AVAILABLE(10_11,9_0);
//加载本地 HTML字符串
- (nullableWKNavigation*)loadHTMLString:(NSString*)string baseURL:(nullableNSURL*)baseURL;
//加载二进制数据
- (nullableWKNavigation*)loadData:(NSData*)data MIMEType:(NSString*)MIMEType characterEncodingName:(NSString*)characterEncodingName baseURL:(NSURL*)baseURL NS_AVAILABLE(10_11,9_0);
WKWebView 原文网址 :http://www.jianshu.com/p/7bb5f15f1daa
#import"ViewController.h"
#import
@interfaceViewController()
//webView
@property(nonatomic,strong)WKWebView*webView;
//进度条
@property(nonatomic,strong)UIProgressView*progressView;
@end
@implementationViewController
-(void)viewWillDisappear:(BOOL)animated{
[superviewWillDisappear:animated];
//移除监听
[self.webViewremoveObserver:selfforKeyPath:@"loading"];
[self.webViewremoveObserver:selfforKeyPath:@"title"];
[self.webViewremoveObserver:selfforKeyPath:@"estimatedProgress"];
}
- (void)viewDidLoad {
[superviewDidLoad];
[selfcreatWebView];
[selfcreatProgressView];
//添加KVO监听
[self.webViewaddObserver:self
forKeyPath:@"loading"
options:NSKeyValueObservingOptionNew
context:nil];
[self.webViewaddObserver:self
forKeyPath:@"title"
options:NSKeyValueObservingOptionNew
context:nil];
[self.webViewaddObserver:self
forKeyPath:@"estimatedProgress"
options:NSKeyValueObservingOptionNew
context:nil];
self.navigationItem.leftBarButtonItem= [[UIBarButtonItemalloc]initWithTitle:@"后退"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(goback)];
self.navigationItem.rightBarButtonItem= [[UIBarButtonItemalloc]initWithTitle:@"前进"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(gofarward)];
}
-(void)goback{
if([self.webViewcanGoBack]) {
[self.webViewgoBack];
NSLog(@"back");
}
}
-(void)gofarward{
if([self.webViewcanGoForward]) {
[self.webViewgoForward];
}
}
-(void)creatProgressView{
self.progressView= [[UIProgressViewalloc]initWithFrame:self.view.bounds];
self.progressView.backgroundColor= [UIColorredColor];
[self.viewaddSubview:self.progressView];
}
//创建webView
-(void)creatWebView{
WKWebViewConfiguration*config = [WKWebViewConfigurationnew];
//初始化偏好设置属性:preferences
config.preferences= [WKPreferencesnew];
//The minimum font size in points default is 0;
config.preferences.minimumFontSize=10;
//是否支持JavaScript
config.preferences.javaScriptEnabled=YES;
//不通过用户交互,是否可以打开窗口
config.preferences.javaScriptCanOpenWindowsAutomatically=NO;
//通过JS与webView内容交互
config.userContentController= [WKUserContentControllernew];
//注入JS对象名称senderModel,当JS通过senderModel来调用时,我们可以在WKScriptMessageHandler代理中接收到
[config.userContentControlleraddScriptMessageHandler:selfname:@"senderModel"];
self.webView= [[WKWebViewalloc]initWithFrame:self.view.boundsconfiguration:config];
NSURL*path = [[NSBundlemainBundle]URLForResource:@"WKWebViewText"withExtension:@"html"];
[self.webViewloadRequest:[NSURLRequestrequestWithURL:path]];
[self.viewaddSubview:self.webView];
self.webView.navigationDelegate=self;
self.webView.UIDelegate=self;
}
#pragma mark - KVO监听函数
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void*)context{
if([keyPathisEqualToString:@"title"]) {
self.title=self.webView.title;
}elseif([keyPathisEqualToString:@"loading"]){
NSLog(@"loading");
}
elseif([keyPathisEqualToString:@"estimatedProgress"]){
//estimatedProgress取值范围是0-1;
self.progressView.progress=self.webView.estimatedProgress;
}
if(!self.webView.loading) {
[UIViewanimateWithDuration:0.5animations:^{
self.progressView.alpha=0;
}];
}
}
#pragma mark - WKScriptMessageHandler
-(void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message{
//这里可以通过name处理多组交互
if([message.nameisEqualToString:@"senderModel"]) {
//body只支持NSNumber, NSString, NSDate, NSArray,NSDictionary和NSNull类型
NSLog(@"%@",message.body);
}
}
#pragma mark = WKNavigationDelegate
//在发送请求之前,决定是否跳转
-(void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler{
NSString*hostname = navigationAction.request.URL.host.lowercaseString;
NSLog(@"%@",hostname);
if(navigationAction.navigationType==WKNavigationTypeLinkActivated
&& ![hostnamecontainsString:@".baidu.com"]) {
//对于跨域,需要手动跳转
[[UIApplicationsharedApplication]openURL:navigationAction.request.URL];
//不允许web内跳转
decisionHandler(WKNavigationActionPolicyCancel);
}else{
self.progressView.alpha=1.0;
decisionHandler(WKNavigationActionPolicyAllow);
}
}
//在响应完成时,调用的方法。如果设置为不允许响应,web内容就不会传过来
-(void)webView:(WKWebView*)webView decidePolicyForNavigationResponse:(WKNavigationResponse*)navigationResponse decisionHandler:(void(^)(WKNavigationResponsePolicy))decisionHandler{
decisionHandler(WKNavigationResponsePolicyAllow);
}
//接收到服务器跳转请求之后调用
-(void)webView:(WKWebView*)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation*)navigation{
}
//开始加载时调用
-(void)webView:(WKWebView*)webView didStartProvisionalNavigation:(WKNavigation*)navigation{
}
//当内容开始返回时调用
-(void)webView:(WKWebView*)webView didCommitNavigation:(WKNavigation*)navigation{
}
//页面加载完成之后调用
-(void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation{
NSLog(@"title:%@",webView.title);
}
//页面加载失败时调用
- (void)webView:(WKWebView*)webView didFailProvisionalNavigation:(WKNavigation*)navigation
{
}
#pragma mark WKUIDelegate
//alert警告框
-(void)webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(void))completionHandler{
UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"警告"message:@"调用alert提示框"preferredStyle:UIAlertControllerStyleAlert];
[alertaddAction:[UIAlertActionactionWithTitle:@"OK"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
completionHandler();
}]];
[selfpresentViewController:alertanimated:YEScompletion:nil];
NSLog(@"alert message:%@",message);
}
//confirm确认框
-(void)webView:(WKWebView*)webView runJavaScriptConfirmPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(BOOL))completionHandler{
UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"确认框"message:@"调用confirm提示框"preferredStyle:UIAlertControllerStyleAlert];
[alertaddAction:[UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
completionHandler(YES);
}]];
[alertaddAction:[UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:^(UIAlertAction*_Nonnullaction) {
completionHandler(NO);
}]];
[selfpresentViewController:alertanimated:YEScompletion:NULL];
NSLog(@"confirm message:%@", message);
}
- (void)webView:(WKWebView*)webView runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt defaultText:(nullableNSString*)defaultText initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(NSString*__nullableresult))completionHandler {
UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"输入框"message:@"调用输入框"preferredStyle:UIAlertControllerStyleAlert];
[alertaddTextFieldWithConfigurationHandler:^(UITextField*_NonnulltextField) {
textField.textColor= [UIColorblackColor];
}];
[alertaddAction:[UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
completionHandler([[alert.textFieldslastObject]text]);
}]];
[selfpresentViewController:alertanimated:YEScompletion:NULL];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
"WKWebViewText.html" JavaScript 代码
iOS与H5交互练习
*{
font-size:50px;
}
一起来学习吧!
Click me here:http://www.baidu.com">百度
functioncallJsAlert() {
alert('Please show alert');
window.webkit.messageHandlers.senderModel.postMessage({body:'Alert'});
}
functioncallJsConfirm() {
if(confirm('Confirm','Please show confirm')) {
document.getElementById('jsParamFuncSpan').innerHTML
='true';
}else{
document.getElementById('jsParamFuncSpan').innerHTML
='false';
}
window.webkit.messageHandlers.senderModel.postMessage({body:'Confirm'});
}
functioncallJsInput() {
varresponse = prompt('Hello','Please input a Text:');
document.getElementById('jsParamFuncSpan').innerHTML = response;
window.webkit.messageHandlers.senderModel.postMessage({body: response});
}
网友评论