iOS WKWebView基础使用

很久没有写博客了,这两天在使用WKWebView,想记录一下。
WKWebView和UIWebView我就不比较了,网上很多大牛都做了详细分析。
一、初始化WKWebView

   WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
    config.preferences = [WKPreferences new];
    config.preferences.minimumFontSize = 50;
    [config.userContentController addScriptMessageHandler:self name:@"StartClick"];
    WKWebView * webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
 //NSURL * testUrl = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil];
    NSURLRequest * request = [NSURLRequest requestWithURL:self.nextUrl];
    [webView loadRequest:request];
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    [self.view addSubview:webView];
  1. config.preferences里面可以设置一些偏好信息,比如字号,注入交互等。
  2. 初始化WKWebView的时候,使用[[NSBundle mainBundle] URLForResource:@"xxx.html" withExtension:nil];可以加载本地的html文件。

二、导航代理WKNavigationDelegate

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    //内容开始返回
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    //内容加载结束
    //获取手机当前连接的Wi-Fi
    NSString * ssid = [self SSID];
    //调用js方法,注入数据
    NSString * js = [NSString stringWithFormat:@"setWifiName('%@')",ssid];
    [webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@",[error localizedDescription]);
        }else{
            NSLog(@"注入成功!");
        }
    }];
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    //是否跳转到链接页面
    NSString * url = navigationAction.request.URL.absoluteString;
    NSURL * desUrl = [[NSBundle mainBundle] URLForResource:@"CustomerPage.html" withExtension:nil];
    NSString * desUrlStr = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] URLForResource:@"CustomerPage.html" withExtension:nil]];
    if ([url isEqualToString:desUrlStr]) {
        //跳转
        CustomerViewController * customerVC = [[CustomerViewController alloc] init];
        customerVC.nextUrl = desUrl;
        [self.navigationController pushViewController:customerVC animated:YES];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

三、UI代理WKUIDelegate

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    //弹出js的警告框
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"警告" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * actionOne = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"actionOne");
    }];
    [alertController addAction:actionOne];
    [self presentViewController:alertController animated:YES completion:nil];
    completionHandler();
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler
{
    //弹出选择框
    NSLog(@"%s",__func__);
    completionHandler(YES);
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler
{
    //弹出输入框
    NSLog(@"%s",__func__);
    completionHandler(defaultText);
}

四、JS交互WKScriptMessageHandler

- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message
{
      //[config.userContentController addScriptMessageHandler:self name:@"StartClick"];
      //message.name是定义的方法,例如StartClick,message.body是传的值
      //使用此方法,需要在js代码里面加入window.webkit.messageHandlers..postMessage()
      //例如:window.webkit.messageHandlers.StartClick.postMessage({ssid:ss,password:pwd,otherInfo:other,versionID:version});
      if ([message.name isEqualToString:@"StartClick"]) {

        NSString * other = message.body[@"otherInfo"];
        NSString * pwd = message.body[@"password"];
        NSString * ssid = message.body[@"ssid"];
        NSInteger version = [message.body[@"versionID"] integerValue];
    }
}

你可能感兴趣的:(iOS WKWebView基础使用)