iOS WKWebView使用

之前项目都是UIWebView实现的,最近改成了WKWebView ,下面一起学习下(含有demo):
一、WKWebView的优势

  • 性能高,稳定性好,占用的内存比较小,
  • 支持JS交互
  • 支持HTML5 新特性
  • 可以添加进度条

二、具体使用

1、首先需要导入库文件

#import <WebKit/WebKit.h>

2、继承代理事件

WKNavigationDelegate,WKUIDelegate 

3、创建WKWebView

- (WKWebView *)webView {
    if (!_webView) {
         // 进行配置控制器
         WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
         // 实例化对象
         configuration.userContentController = [WKUserContentController new];
         // 调用JS方法
        [configuration.userContentController addScriptMessageHandler:self name:@"uploadPersonImage"];
        //window.webkit.messageHandlers.uploadPersonImage.postMessage({body: 'goodsId=1212'}); js调用
        // 进行偏好设置
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptEnabled = YES;
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        preferences.minimumFontSize = 40.0;
        configuration.preferences = preferences;
    
        _webView = [[WKWebView alloc] initWithFrame:RECT(0, heightWebView, SCREENWIDTH, SCREENHEIGHT- heightWebView) configuration:configuration];
        _webView.navigationDelegate = self;
        _webView.opaque = NO;
        _webView.backgroundColor = [UIColor whiteColor];
        if (@available(ios 11.0,*)){ _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;}
     }
     return _webView;
}

4、实现WKNavigationDelegate代理方法

// 页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    LHLog(@"页面开始加载时调用");
    
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    LHLog(@"当内容开始返回时调用");
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//这里修改导航栏的标题,动态改变
    LHLog(@"页面加载完成之后调用");
    
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    LHLog(@"页面加载失败时调用");
}
// 接收到服务器跳转请求之后再执行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    LHLog(@"接收到服务器跳转请求之后再执行");
}
// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    LHLog(@"在收到响应后,决定是否跳转");
    LHLog(@"%@",navigationResponse);
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的,不然会异常
    decisionHandler(actionPolicy);
}
// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    LHLog(@"在发送请求之前,决定是否跳转");
    //这句是必须加上的,不然会异常
    decisionHandler(WKNavigationActionPolicyAllow);
    NSURL *requestURL = navigationAction.request.URL;
        LHLog(@"-----%@",requestURL.absoluteString);
}

5、实现WKUIDelegate代理事件,主要实现与js的交互

//显示一个JS的Alert(与JS交互)

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
}

//弹出一个输入框(与JS交互的)
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{     
}

//显示一个确认框(JS的)

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
}

5、加载数据

  • 加载服务器链接
    带参数

    NSString * urlS = [NSString stringWithFormat:@"https://www.baidu.com?q=w"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlS]]];
    

    不带参数

    NSString * urlS = [NSString stringWithFormat:@"https://www.baidu.com"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlS]]];
    
  • 加载本地的html 这样有的会出现图片样式不显示的情况, 解决办法 : Added folders 选择 Create folder
    references ;或者将文件压缩,拖到项目中,然后解压到沙盒目录下

    不带参数

     NSString * pathString = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"app/html"];    //app/html 是html文件在项目中的目录
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pathString]]];
    

    带参数

    NSString * pathString = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"app/html"];    //app/html 是html文件在项目中的目录
    NSString * urlString2 = [[NSString stringWithFormat:@"?sid=%@",GETUSERDEFAULT(@"cookie")]stringByAddingPercentEncodingWithAllowedCharacters:  [NSCharacterSet URLFragmentAllowedCharacterSet]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString2 relativeToURL:[NSURL fileURLWithPath:pathString]]]];
    
  • 加载沙盒

    带参数

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * path = [paths objectAtIndex:0];
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/app/html/index.html"]];
    NSString * urlString2 = [[NSString stringWithFormat:@"?sid=%@",GETUSERDEFAULT(@"cookie")]stringByAddingPercentEncodingWithAllowedCharacters:    [NSCharacterSet URLFragmentAllowedCharacterSet]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString2 relativeToURL:[NSURL fileURLWithPath:path]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.f]];
    

    不带参数

     NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString * path = [paths objectAtIndex:0];
     path = [path stringByAppendingString:[NSString stringWithFormat:@"/app/html/index.html"]];
     NSString * urlString1 = [[NSString stringWithFormat:@"%@",path] stringByAddingPercentEncodingWithAllowedCharacters:   [NSCharacterSet URLFragmentAllowedCharacterSet]];
    

以上就是WKwebView的具体使用 demo下载

猜你喜欢

转载自blog.csdn.net/u013983033/article/details/84027078