iOS学习笔记 — WKWebView的使用

使用WKWebView需要引入头文件

#import <WebKit/WebKit.h>

初始化

/**
创建WKWebView
*/
- (WKWebView *)webViewWithSuperView:(UIView *)superView requestURLStr:(NSString *)requestStr target:(id)target andMasonryBlock:(MasonryBlock)masonryBlock
{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.mediaTypesRequiringUserActionForPlayback = false;
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    [superView addSubview:webView];
    webView.allowsBackForwardNavigationGestures = YES;//开启了支持滑动返回
    webView.scrollView.bounces = NO;
    webView.UIDelegate = target;
    webView.navigationDelegate = target;
    
    NSURL *url = [NSURL URLWithString:requestStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    
    if (masonryBlock) {
        [webView mas_makeConstraints:^(MASConstraintMaker *make) {
            masonryBlock(make);
        }];
    }
    return webView;
}

获取WKWebView的网页内容高度

获取WKWebView的网页内容高度的方法在WKNavigationDelegate里:

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable data, NSError * _Nullable error) {

        self.webViewHeight = [data floatValue];

        [self.myTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

如果通过该方法获取网页高度,发现HTML5字体内容变小,可以通过向网页内容中注入JS代码(亲测有效)解决。

改变一下WKWebView的初始化方法:

NSString *source = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *contentController = [[WKUserContentController alloc] init];
    [contentController addUserScript:userScript];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = contentController;
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];

WKWebView显示JS的弹窗

WKWebView不像UIWebView一样会显示JS的弹窗,显示JS弹窗的方法在WKUIDelegate里:

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    //我这里使用第三方HUD展示弹窗内容
    if ([HELPER isBlankString:message] == NO) {
        [HELPER showText:message statusType:TextStatusTypeMidden];
    }
    
    completionHandler();
}

WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [HELPER progressHUDWithText:@"加载中" inView:self.view];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [HELPER hideHUDForView:self.view];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [HELPER hideHUDForView:self.view];
}

WKWebView与JS的交互

1.JS调用Objective-C的方法:

首先需要在viewWillAppear方法里添加ScriptMessageHandler,并指定方法名,例如“share”。还需要在viewWillDisappear里移除Handler。

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.myWebView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //这里要记得移除Handler
    [self.myWebView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"];
}

JS调用Objective-C的方法在WKScriptMessageHandler里实现。

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    // "Share" 是监听交互的方法名
    if ([message.name isEqualToString:@"Share"]) {

        NSLog(@"%@",message.body);
    }
}

2.Objective-C调用JS的方法:

 // callJS()是JS方法名
[self.webView evaluateJavaScript:[NSString stringWithFormat:@"callJS('%@','%@')", @"Js参数",@"Js参数"] completionHandler:nil];
本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]]]; */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值