WKWebView在实际开发中的使用汇总
最近公司的项目中大量使用了webview加载H5,鉴于WKWebView的性能优于UIWebView,所以就选择了WKWebView。WKWebView在使用的过程中,还是有很过内容值得我们去记录和研究的,这里我就做了一下总结,跟大家分享一下。文章中的示例代码可以到github中下载查看。
一、基本使用
WKWebView的基本使用网上也有很多,这里我就简略的写一下:
引入头文件#import <WebKit/WebKit.h>
- (void)setupWebview{
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;
WKWebView *webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - 64) configuration:config];
[self.view addSubview:webview];
/* 加载服务器url的方法*/
NSString *url = @"https://www.baidu.com";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[webview loadRequest:request];
webview.navigationDelegate = self;
webview.UIDelegate = self;
}
WKWebViewConfiguration和WKPreferences中有很多属性可以对webview初始化进行设置,这里就不一一介绍了。
遵循的协议和实现的协议方法:
#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);
}
下面介绍几个开发中需要实现的小细节:
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<NSKeyValueChangeKey,id> *)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"];
}
}
下面是实现的效果图:
效果图-1.gif
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的信息。
二、原生JS交互
(一)JS调用原生方法
在WKWebView中实现与JS的交互还需要实现另外一个代理方法:WKScriptMessageHandler
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message
在 message
的name
和body
属性中我们可以获取到与JS调取原生的方法名和所传递的参数。
效果图-3.jpg打印一下如下图所示:
JS调用原生方法的代码:
window.webkit.messageHandlers.takePicturesByNative.postMessage({
"picType": "0",
"picCount":"9",
"callBackName": "getImg"
})
}
注意:JS只能向原生传递一个参数,所以如果有多个参数需要传递,可以让JS传递对象或者JSON字符串即可。
(二)原生调用JS方法
[webview evaluateJavaScript:“JS语句” completionHandler:^(id _Nullable data, NSError * _Nullable error) {
}];
下面举例说明:
实现H5通过原生方法调用相册
首先,遵循代理:
<WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler>
注册方法名:
config.preferences = preferences;
WKUserContentController *user = [[WKUserContentController alloc]init];
[user addScriptMessageHandler:self name:@"takePicturesByNative"];
config.userContentController =user;
实现代理方法:
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message{
if ([message.name isEqualToString:@"takePicturesByNative"]) {
[self takePicturesByNative];
}
}
- (void)takePicturesByNative{
UIImagePickerController *vc = [[UIImagePickerController alloc] init];
vc.delegate = self;
vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:vc animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
NSTimeInterval timeInterval = [[NSDate date]timeIntervalSince1970];
NSString *timeString = [NSString stringWithFormat:@"%.0f",timeInterval];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",timeString]]; //保存到本地
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
NSString *str = [NSString stringWithFormat:@"%@",filePath];
[picker dismissViewControllerAnimated:YES completion:^{
// oc 调用js 并且传递图片路径参数
[self.webview evaluateJavaScript:[NSString stringWithFormat:@"getImg('%@')",str] completionHandler:^(id _Nullable data, NSError * _Nullable error) {
}];
}];
}
我们期望的效果是,点击webview中打开相册
的按钮,调用原生方法,展示相册,选择图片,可以传递给JS,并展示在webview中。
但是运行程序发现:我们可以打开相册,说明JS调用原生方法成功了,但是并不能在webview中展示出来,说明原生调用JS方法时,出现了问题。这是因为,在WKWebView中,H5在加载本地的资源(包括图片、CSS文件、JS文件等等)时,默认被禁止了,所以根据我们传递给H5的图片路径,无法展示图片。解决办法:在传递给H5的图片路径中添加我们自己的请求头,拦截H5加载资源的请求头进行判断,拿到路径然后由我们来手动请求。
先为图片路径添加一个我们自己的请求头:
NSString *str = [NSString stringWithFormat:@"myapp://%@",filePath];
然后创建一个新类继承于NSURLProtocol
.h
#import <UIKit/UIKit.h>
@interface MyCustomURLProtocol : NSURLProtocol
@end
.m
@implementation MyCustomURLProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest{
if ([theRequest.URL.scheme caseInsensitiveCompare:@"myapp"] == NSOrderedSame) {
return YES;
}
return NO;
}
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)theRequest{
return theRequest;
}
- (void)startLoading{
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[self.request URL]
MIMEType:@"image/png"
expectedContentLength:-1
textEncodingName:nil];
NSString *imagePath = [self.request.URL.absoluteString componentsSeparatedByString:@"myapp://"].lastObject;
NSData *data = [NSData dataWithContentsOfFile:imagePath];
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
}
- (void)stopLoading{
}
@end
在控制器中注册MyCustomURLProtocol协议并添加对myapp协议的监听:
//注册
[NSURLProtocol registerClass:[MyCustomURLProtocol class]];
//实现拦截功能
Class cls = NSClassFromString(@"WKBrowsingContextController");
SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
if ([(id)cls respondsToSelector:sel]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[(id)cls performSelector:sel withObject:@"myapp"];
#pragma clang diagnostic pop
}
运行程序,效果如下:
效果图-2.gif
不仅仅是加载本地的图片,webview加载任何本地的资源都可以使用该方法,不过在使用过程中,大家一定要密切注意跨域问题会带来的安全性问题。
结尾
关于WKWebView其实还有很多内容,接下来我还会继续深入地去探究WKWebView的原理和使用。