iOS wkwebview 加载html

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012490014/article/details/80533798

wkwebview的优势

1.交互更方便

2.更低的内存占用

3.高达60fps的滚动刷新率以及内置手势

4.支持更多的HTML5特性

5.基于webkit内核,支持Nitro JavaScript引擎

6.提供常用的属性,如加载网页进度的属性estimatedProgress

wkwebview的使用

首先需要引入头文件

#import <WebKit/WebKit.h>

js调用oc

配置configuration

WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];
//注册方法
        [configuration.userContentController addScriptMessageHandler:self name:@"方法名"];

        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.scrollView.bounces = NO;


实现协议:

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@" NSStringFromSelector(_cmd) == %@ \n",NSStringFromSelector(_cmd));
    NSLog(@"message.body%@ \n name:%@",message.body,message.name);
    if ([message.name isEqualToString:@"方法名"]) {
       
    }else {
        
    }
}

js调用oc,html5写法:window.webkit.messageHandlers.方法名.postMessage(参数)

oc调用js:

NSString *js = @"name('参数')";
[self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
      NSLog(@"response:%@..error:%@",response,error);
}];

wkwebview使用时遇到的问题

用wkwebview加载本地html(如果把下砸的html文件放到沙盒里)的时候会出现,加载不了图片的问题,这是因为沙盒的安全机制,使用Apple提供的另外一个API用户访问本地文件:

[self.webView loadFileURL:[NSURL fileURLWithPath:filePath] allowingReadAccessToURL:baseURL];
其中:
- filePath是需要显示的文件路径,这个目录指的是HTML的文件路径。
- baseURL是需要访问的相关文件的目录。这个目录包括HTML文件本身和用到的资源,比如图片等。

猜你喜欢

转载自blog.csdn.net/u012490014/article/details/80533798