iOS WKWebView的使用

一、导入依赖库
WebKit
二、创建WebView
//1. 创建配置项
WKWebViewConfiguration *configuration = [[ WKWebViewConfiguration alloc ] init ];
//1.1 设置偏好
configuration.
preferences = [[ WKPreferences alloc ] init ];
configuration.
preferences . minimumFontSize = 10 ;
configuration.
preferences . javaScriptEnabled = YES ;
// 默认是不能通过 JS 自动打开字典的,必须通过用户交互才能打开
configuration.
preferences . javaScriptCanOpenWindowsAutomatically = NO ;

//1.2 设置内容交互配置
configuration.
userContentController = [[ WKUserContentController alloc ] init ];
//1.2.1 添加一个 JS Html 中,这样就可以直接在 JS 调用我们添加的 JS 方法
WKUserScript *script = [[ WKUserScript alloc ] initWithSource : @"function showAlert()" injectionTime : WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly : YES ];
[configuration.
userContentController addUserScript :script];

//2. 创建 WKWebView
WKWebView *browse = [[ WKWebView alloc ] initWithFrame : self . view . frame configuration :configuration];
//2.1 设置代理
browse.
navigationDelegate = self ;
browse.
UIDelegate = self ;
//2.2 设置需要加载的链接
NSString *urlStr = @"" ;
[browse
loadHTMLString :urlStr baseURL : nil ];

[
self . view addSubview :browse];

/*
 *  goBack     
后退
 *  goForward  
前进
 * 
监听通知: loading title estimatedProgress 动能对应为:是否正在加载中、页面的标题、页面内容加载进度
 */
三、实现代理
#pragma mark - WKUIDelegate
#pragma mark HTML
中的 alert
- ( void )webView:( WKWebView *)webView runJavaScriptAlertPanelWithMessage:( NSString *)message initiatedByFrame:( WKFrameInfo *)frame completionHandler:( void (^)( void ))completionHandler
{
    completionHandler();
}

#pragma mark HTML 中的 confirm
- ( void )webView:( WKWebView *)webView runJavaScriptConfirmPanelWithMessage:( NSString *)message initiatedByFrame:( WKFrameInfo *)frame completionHandler:( void (^)( BOOL ))completionHandler
{
    completionHandler(
YES );
}

#pragma mark HTML 中的 prompt
- ( void )webView:( WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:( NSString *)prompt defaultText:( NSString *)defaultText initiatedByFrame:( WKFrameInfo *)frame completionHandler:( void (^)( NSString * _Nullable ))completionHandler
{
    completionHandler(
@"success" );
}

#pragma mark - WKScriptMessageHandler
- ( void )userContentController:( WKUserContentController *)userContentController didReceiveScriptMessage:( WKScriptMessage *)message
{
   
// js 端通过 window.webkit.messageHandlers.{InjectedName}.postMessage() 方法来发送消息到 native ,通过这个代理可以接收到消息并做相应的处理。
}

#pragma mark - WKNavigationDelegate
#pragma mark
是否允许跳转导航,如果不允许可以手动跳转 [[UIApplication sharedApplication] openURL:@""];
- ( void )webView:( WKWebView *)webView decidePolicyForNavigationAction:( WKNavigationAction *)navigationAction decisionHandler:( void (^)( WKNavigationActionPolicy ))decisionHandler
{
    decisionHandler(
WKNavigationActionPolicyAllow );
}

#pragma mark 开始加载页面
- ( void )webView:( WKWebView *)webView didStartProvisionalNavigation:( WKNavigation *)navigation
{

}

#pragma mark 决定是否允许导航响应,如果不允许就不会跳转到链接的页面
- ( void )webView:( WKWebView *)webView decidePolicyForNavigationResponse:( WKNavigationResponse *)navigationResponse decisionHandler:( void (^)( WKNavigationResponsePolicy ))decisionHandler
{
    decisionHandler(
WKNavigationResponsePolicyAllow );
}

#pragma mark 内容开始返回
- ( void )webView:( WKWebView *)webView didCommitNavigation:( WKNavigation *)navigation
{
   
}

#pragma mark 加载完成
- ( void )webView:( WKWebView *)webView didFinishNavigation:( WKNavigation *)navigation
{

}

#pragma mark 加载失败
- ( void )webView:( WKWebView *)webView didFailNavigation:( WKNavigation *)navigation withError:( NSError *)error
{


}

#pragma mark 如果我们需要处理在重定向时,需要实现下面的代理方法就可以接收到
- ( void )webView:( WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:( WKNavigation *)navigation
{

}

#pragma mark 如果我们的请求要求授权、证书等,我们需要处理下面的代理方法,以提供相应的授权处理等
- ( void )webView:( WKWebView *)webView didReceiveAuthenticationChallenge:( NSURLAuthenticationChallenge *)challenge completionHandler:( void (^)( NSURLSessionAuthChallengeDisposition , NSURLCredential * _Nullable ))completionHandler
{
   
NSURLCredential *credential = [[ NSURLCredential alloc ] init ];
    completionHandler(
NSURLSessionAuthChallengeUseCredential ,credential);
}

#pragma mark 当我们终止页面加载时,我们会可以处理下面的代理方法,如果不需要处理,则不用实现之
- ( void )webViewWebContentProcessDidTerminate:( WKWebView *)webView
{

}
本demo是WKWebView的基本使用和交互 ,实现了原生调用js的方法、js调用原生的方法、通过拦截进行交互的方法;修改内容 加入沙盒 / /加载沙盒 不带参数 // NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // NSString * path = [paths objectAtIndex:0]; // path = [path stringByAppendingString:[NSString stringWithFormat:@"/app/html/index.html"]]; // NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"file://%@",path] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]] relativeToURL:[NSURL fileURLWithPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject]]; // [self.wkView loadFileURL:url allowingReadAccessToURL:[NSURL fileURLWithPath: [paths objectAtIndex:0]]]; // 带参数 /* NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * path = [paths objectAtIndex:0]; path = [path stringByAppendingString:[NSString stringWithFormat:@"/app/html/index.html"]]; NSURL * url = [NSURL fileURLWithPath:path isDirectory:NO]; NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO]; [queryItemArray addObject:[NSURLQueryItem queryItemWithName:@"version" value:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]]]; [urlComponents setQueryItems:queryItemArray]; [self.wkView loadFileURL:urlComponents.URL allowingReadAccessToURL:[NSURL fileURLWithPath: [paths objectAtIndex:0]]]; */
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值