iOS WKWebView使用

本文详细介绍WKWebView相较于UIWebView的优势,包括高性能、稳定性、内存优化、JS交互及HTML5支持等。通过具体代码示例,讲解如何配置WKWebView,实现与JS的交互,以及加载网页和本地HTML的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前项目都是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"]];
    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]]];

    不带参数

    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]]];

以上就是WKwebView的具体使用 demo下载 (demo中加载沙盒是用的loadRequest 被苹果禁止了,麻烦用文章中的方法加载)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值