一、基本使用
引入头文件#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;
}
遵循的协议和实现的协议方法:
#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 *)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"];
}
}
二、原生JS交互
(一)JS调用原生方法
在WKWebView中实现与JS的交互还需要实现另外一个代理方法:WKScriptMessageHandler
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message
在 message的name和body属性中我们可以获取到与JS调取原生的方法名和所传递的参数。
二)原生调用JS方法
[webview evaluateJavaScript:“JS语句” completionHandler:^(id _Nullable data, NSError * _Nullable error) {
}];
下面举例说明:
首先,遵循代理:
<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 *)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
@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
}