最近公司有做APP中嵌套 H5的业务;鉴于WKWebView的性能优于UIWebView,所以就选择了WKWebView。WKWebView在使用的过程中,遇到一些问题,这里我就做了一下总结,跟大家分享一下。
一. 基本使用
引入头文件#import
1> 初始化
- (WKWebView *)webView{
if (!__webView) {
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.selectionGranularity = WKSelectionGranularityDynamic;
config.allowsInlineMediaPlayback = YES;
WKPreferences *preferences = [WKPreferences new];
//是否支持JavaScript
preferences.javaScriptEnabled = YES;
//不通过用户交互,是否可以打开窗口
preferences.javaScriptCanOpenWindowsAutomatically = YES;
config.preferences = preferences;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - 64) configuration:config];
[self.view addSubview:_webView];
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
}
return _webView;
}
/* 加载服务器url的方法*/
- (void)setURL:(NSString*)URL {
_URL= URL;
// NSString *url = @"https://www.baidu.com";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
[_webView loadRequest:request];
}
WKWebViewConfiguration和WKPreferences中有很多属性可以对webview初始化进行设置,这里就不一一介绍了。
2> 遵循的协议和实现的协议方法:
#pragma mark - WKNavigationDelegate
/* 页面开始加载 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
}
/* 开始返回内容 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
}
/* 页面加载完成 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
}
/* 页面加载失败 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
}
/* 在发送请求之前,决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
//允许跳转
decisionHandler(WKNavigationActionPolicyAllow);
//不允许跳转
//decisionHandler(WKNavigationActionPolicyCancel);
}
/* 在收到响应后,决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
NSLog(@"%@",navigationResponse.response.URL.absoluteString);
//允许跳转
decisionHandler(WKNavigationResponsePolicyAllow);
//不允许跳转
//decisionHandler(WKNavigationResponsePolicyCancel);
}
3>下面介绍几个开发中需要实现的小细节:
1、url中文处理
有时候我们加载的URL中可能会出现中文,需要我们手动进行转码,但是同时又要保证URL中的特殊字符保持不变,那么我们就可以使用下面的方法(方法放到了NSString中的分类中):
- (NSURL *)url{
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
return [NSURL URLWithString:(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL,kCFStringEncodingUTF8))];
#pragma clang diagnostic pop
}
2、获取h5中的标题 3、添加进度条
获取h5中的标题和添加进度条放到一起展示看起来更明朗一点,在初始化wenview时,添加两个观察者分别用来监听webview 的estimatedProgress和title属性:
webview.navigationDelegate = self;
webview.UIDelegate = self;
[webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[webview addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
添加创建进度条,并添加进度条图层属性:
@property (nonatomic,weak) CALayer *progressLayer;
-(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 = [UIColor greenColor].CGColor;
[progress.layer addSublayer:layer];
self.progressLayer = layer;
}
实现观察者的回调方法:
#pragma mark - KVO回馈
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)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.title = change[@"new"];
}
}
4、添加userAgent信息
有时候H5的伙伴需要我们为webview的请求添加userAgent,以用来识别操作系统等信息,但是如果每次用到webview都要添加一次的话会比较麻烦,下面介绍一个一劳永逸的方法。
在Appdelegate中添加一个WKWebview的属性,启动app时直接,为该属性添加userAgent:
- (void)setUserAgent {
_webView = [[WKWebView alloc] initWithFrame:CGRectZero];
[_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
if (error) { return; }
NSString *userAgent = result;
if (![userAgent containsString:@"/mobile-iOS"]) {
userAgent = [userAgent stringByAppendingString:@"/mobile-iOS"];
NSDictionary *dict = @{@"UserAgent": userAgent};
[TKUserDefaults registerDefaults:dict];
}
}];
}
这样一来,在app中创建的webview都会存在我们添加的userAgent的信息。
二.iOS 原生JS交互
在WKWebView中实现与JS的交互还需要实现另外一个代理方法:WKScriptMessageHandler
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message
在 message的name和body属性中我们可以获取到与H5(JS)调取原生的方法名和所传递的参数。
1> H5(JS)中要写的方法:
window.webkit.messageHandlers.theMethodOfCallingOC.postMessage({
"picType": "0",
"picCount":"9";
})
}
theMethodOfCallingOC,需要OC 实现的方法, message中传的是参数;
注意:H5(JS)只能向原生传递一个参数,所以如果有多个参数需要传递,可以让H5(JS)传递对象或者JSON字符串即可。
2> OC调用H5(JS)方法
[webview evaluateJavaScript:“JS语句” completionHandler:^(id _Nullable data, NSError * _Nullable error) {
}];
我们举例使用一下
首先,遵循代理:
注册方法名:
config.preferences = preferences;
WKUserContentController *user = [[WKUserContentController alloc]init];
[user addScriptMessageHandler:self name:@"theMethodOfCallingOC"];
config.userContentController =user;
实现代理方法:
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"方法名:%@", message.name);
NSLog(@"参数:%@", message.body);
// 方法名
NSString *methods = [NSString stringWithFormat:@"%@:", message.name];
SEL selector =NSSelectorFromString(methods);
// 调用方法
if([selfrespondsToSelector:selector]) {
[selfperformSelector:selectorwithObject:message.body];
}else{
NSLog(@"未实行方法:%@", methods);
}
}
- (void)theMethodOfCallingOC:(NSString*)message{
}
最后需要删除掉注册的方法
- (void)dealloc{
//这里需要注意,前面增加过的方法一定要remove掉。
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"theMethodOfCallingOC"];
}
but,但是我无意间发现自从注册了"theMethodOfCallingOC"方法后,控制器一直释放不了.
[_webView.configuration.userContentController addScriptMessageHandler:self name:@"theMethodOfCallingOC"];
看了半天,将这个 self改成弱引用还是释放不了,具体原因不太清楚,还有待研究,欢迎一起探讨;
解决方案:
.h
#import
#import
@protocol WKDelegate
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message;
@end
@interface WKDelegateViewController : UIViewController
@property (weak , nonatomic) id delegate;
@end
.m
#import "WKDelegateViewController.h"
@interface WKDelegateViewController ()
@end
@implementationWKDelegateViewController
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message{
if([self.delegaterespondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
[self.delegate userContentController:userContentController didReceiveScriptMessage:message];
}
}
@end
具体实现:
(一)遵守协议
(二)定义全局变量
@property(nonatomic,strong)WKUserContentController* userContentController;
(三)初始化
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
self.userContentController = [[WKUserContentController alloc] init];
configuration.userContentController=self.userContentController;
//注册方法
WKDelegateViewController * delegateController = [[WKDelegateViewController alloc] init];
delegateController.delegate=self;
[self.userContentControlleraddScriptMessageHandler:delegateController name:@"theMethodOfCallingOC"];
configuration.preferences= preferences;
WKWebView*h5webView = [[WKWebViewalloc]initWithFrame:webBoundsconfiguration:configuration];
(四)最后销毁
- (void)dealloc{
//这里需要注意,前面增加过的方法一定要remove掉。
[self.userContentController removeScriptMessageHandlerForName:@"theMethodOfCallingOC"];
}
OK,可以释放了,哪里有不对的,请多多指教.