iOS开发基础146-深入解析WKWebView

WKWebView 深度解析:多进程架构、JS 交互、性能优化与跨平台方案原理

本文系统梳理 WKWebView:多进程底层架构、基本使用与加载、WKNavigationDelegate/WKUIDelegate 代理、WKScriptMessageHandler 双向通信、进度条与文件上传、性能优化、OC 与 JS 四种传参方式; React Native、Flutter、Weex、Cordova、小程序等主流跨平台方案的底层原理。


一、WKWebView 底层架构

WKWebView 基于 WebKit 框架,采用多进程架构,将页面渲染、JS 执行、网络请求放在独立进程中,与主 App 进程隔离,显著提升稳定性和安全性。

1. 三大进程

进程 进程名(iOS) 职责
UI 进程 App 主进程 WKWebView 对象所在进程,负责用户交互、接收输入、通过 XPC 与 Web 进程通信
Web 内容进程 com.apple.WebKit.WebContent HTML 解析、CSS 解析、JS 执行(Nitro 引擎)、页面渲染、布局计算
网络进程 com.apple.WebKit.Networking 网络请求管理、HTTP/HTTPS、缓存(Network Cache)、Cookie 存储

进程间通过 XPC(iOS 上的进程间通信机制)传递消息。Web 内容进程崩溃不会导致 App 崩溃,App 会收到 webViewWebContentProcessDidTerminate: 回调,可在此重新加载页面。

2. 架构示意

┌─────────────────────────────────────────────────────────┐
│                     UI 进程(App 主进程)                  │
│  ┌──────────────┐         ┌──────────────────────────┐  │
│  │  WKWebView   │◄──XPC──►│  WKProcessPool / 消息代理 │  │
│  └──────────────┘         └────────────┬─────────────┘  │
└──────────────────────────────────────────┼───────────────┘
                                           │ XPC
                    ┌──────────────────────┼──────────────────────┐
                    ▼                                             ▼
        ┌───────────────────────┐                   ┌───────────────────────┐
        │    Web 内容进程         │                   │      网络进程           │
        │  HTML/CSS/JS 解析渲染   │◄─────HTTP/HTTPS──►│  请求/缓存/Cookie      │
        │  Nitro JS 引擎          │                   │  Network Cache         │
        └───────────────────────┘                   └───────────────────────┘

3. 多进程优势

  • 稳定性:Web 进程崩溃不影响 App 主进程。
  • 安全性:Web 内容运行在沙盒进程中,恶意网页无法直接访问 App 内存。
  • 性能:Nitro JS 引擎支持 JIT(即时编译),JS 执行速度比 UIWebView 快数倍;渲染和网络在独立进程,不阻塞主线程。
  • 内存:Web 进程独立分配内存,App 进程内存占用更低。

二、WKWebView 基本使用

1. 初始化

#import <WebKit/WebKit.h>

@interface ViewController ()
@property (nonatomic, strong) WKWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    [self.view addSubview:self.webView];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]]];
}

@end

2. 加载方式

方法 说明
loadRequest: 加载网络请求
loadHTMLString:baseURL: 加载 HTML 字符串
loadData:MIMEType:characterEncodingName:baseURL: 加载二进制数据(PDF/图片等)
loadFileURL:allowingReadAccessToURL: 加载沙盒本地文件(iOS 9+,需授权读取目录)
// 加载 HTML 字符串
NSString *html = @"<html><body><h1>Hello</h1></body></html>";
[self.webView loadHTMLString:html baseURL:nil];

// 加载沙盒文件(iOS 9+)
NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL.URLByDeletingLastPathComponent];

3. 导航控制

[self.webView reload];           // 刷新
[self.webView reloadFromOrigin]; // 忽略缓存重新加载
[self.webView stopLoading];      // 停止
[self.webView goBack];           // 后退
[self.webView goForward];        // 前进

// 导航状态(只读)
self.webView.canGoBack;
self.webView.canGoForward;
self.webView.loading;
self.webView.estimatedProgress; // 加载进度 0.0~1.0
self.webView.title;             // 页面标题(KVO 监听)
self.webView.URL;               // 当前 URL

4. OC 调用 JS

[self.webView evaluateJavaScript:@"document.title" completionHandler:^(id result, NSError *error) {
    if (!error) {
        NSLog(@"标题: %@", result);
    }
}];

evaluateJavaScript:completionHandler: 是异步的,不阻塞主线程(区别于 UIWebView 的同步方法)。


三、代理与回调

WKWebView 有两个核心代理:WKNavigationDelegate(导航与加载)和 WKUIDelegate(UI 交互)。

1. WKNavigationDelegate

@interface ViewController () <WKNavigationDelegate>
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.navigationDelegate = self;
}

// 收到服务器重定向(请求跳转)
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"服务器重定向");
}

// 开始加载(请求已发出,等待响应)
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载");
}

// 内容开始返回(已收到响应头,开始接收数据)
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"内容开始返回");
}

// 加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
}

// 加载失败(请求阶段失败,如无网络、URL 错误)
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"请求失败: %@", error);
}

// 加载失败(内容返回后失败,如解析错误)
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败: %@", error);
}

// Web 内容进程崩溃(可在此重新加载)
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@"Web 进程崩溃,重新加载");
    [webView reload];
}

// 拦截请求(决定是否允许导航,类似 UIWebView 的 shouldStartLoadWithRequest)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *url = navigationAction.request.URL.absoluteString;
    if ([url hasPrefix:@"customscheme://"]) {
        // 处理自定义 scheme
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 拦截响应(决定是否允许加载响应内容)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// HTTPS 认证(自签名证书等)
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    } else {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
}

@end

decidePolicyForNavigationAction: 和 decidePolicyForNavigationResponse: 中必须调用 decisionHandler,否则会崩溃。

2. WKUIDelegate

@interface ViewController () <WKUIDelegate>
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.UIDelegate = self;
}

// JS alert
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(); // 必须调用
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

// JS confirm
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

// JS prompt
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入" message:prompt preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.text = defaultText;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alert.textFields.firstObject.text);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(nil);
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

// 新窗口打开(target="_blank" 时调用,需返回新 WKWebView)
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request]; // 在当前 WebView 加载
    }
    return nil;
}

// 文件上传(input type="file")
- (void)webView:(WKWebView *)webView runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSArray<NSURL *> * _Nullable))completionHandler {
    UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.item"] inMode:UIDocumentPickerModeOpen];
    picker.delegate = self;
    // 选择完成后调用 completionHandler 传回文件 URL
    // completionHandler(@[selectedURL]);
    [self presentViewController:picker animated:YES completion:nil];
}

@end

WKUIDelegate 的三个面板方法(alert/confirm/prompt)中必须调用 completionHandler,否则 JS 线程会永久挂起。


四、进阶使用

1. JS 交互(WKScriptMessageHandler)

@interface ViewController () <WKScriptMessageHandler>
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 注册消息处理器(name 对应 JS 端 window.webkit.messageHandlers.<name>)
    [config.userContentController addScriptMessageHandler:self name:@"nativeHandler"];
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    [self.view addSubview:self.webView];
    
    NSString *html = @"<html><body><button onclick=\"window.webkit.messageHandlers.nativeHandler.postMessage({type:'click', data:'hello'})\">Click</button></body></html>";
    [self.webView loadHTMLString:html baseURL:nil];
}

// JS 调用 OC 的回调
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"nativeHandler"]) {
        NSLog(@"JS 消息: %@", message.body); // body 可以是字符串/字典/数组/数字
    }
}

// 必须移除 handler,否则循环引用(addScriptMessageHandler 强引用 delegate)
- (void)dealloc {
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"nativeHandler"];
}

@end

JS 端:

// JS 调用 OC
window.webkit.messageHandlers.nativeHandler.postMessage({type: "click", data: "hello"});

循环引用:addScriptMessageHandler:name: 会强引用 delegate(self),self 强引用 webView,webView 强引用 configuration,形成循环。必须在 dealloc 前调用 removeScriptMessageHandlerForName: 断开引用。

2. 加载进度条(KVO)

@interface ViewController ()
@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.webView];
    
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.frame = CGRectMake(0, 88, self.view.bounds.size.width, 2);
    [self.view addSubview:self.progressView];
    
    // KVO 监听进度和标题
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]]];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        self.progressView.alpha = (self.webView.estimatedProgress >= 1.0) ? 0.0 : 1.0;
    } else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}

@end

3. 自定义 UserAgent

// 追加自定义 UA(在默认 UA 后追加)
[self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
    NSString *defaultUA = result;
    NSString *customUA = [NSString stringWithFormat:@"%@ MyApp/1.0", defaultUA];
    self.webView.customUserAgent = customUA;
}];

五、性能优化

1. 缓存策略

WKWebView 有自己的缓存机制(WebKit Network Cache,独立于 NSURLCache)。NSURLCache 对 WKWebView 的网络请求影响有限,不能完全控制 WKWebView 的缓存。WKWebView 的缓存主要由服务器响应头(Cache-Control、Expires、ETag)控制。

// 请求级缓存策略
NSURLRequest *request = [NSURLRequest requestWithURL:url
                                          cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                      timeoutInterval:30];
[self.webView loadRequest:request];
缓存策略 说明
NSURLRequestUseProtocolCachePolicy 默认,遵循 HTTP 缓存协议
NSURLRequestReloadIgnoringLocalCacheData 忽略缓存,重新请求
NSURLRequestReturnCacheDataElseLoad 有缓存用缓存,无缓存才请求
NSURLRequestReturnCacheDataDontLoad 只用缓存,无缓存则失败(离线模式)

2. 预加载与初始化优化

  • 提前初始化 WKWebView:WKWebView 首次创建较慢(需启动 Web 进程),可在 App 启动或上级页面提前创建并预加载空白页,使用时直接加载目标 URL。
  • 复用 WKWebView:多个网页页面可复用同一个 WKWebView 实例,避免重复创建 Web 进程的开销。
  • WKProcessPool:多个 WKWebView 共享同一个 WKProcessPool 可复用 Web 进程,降低内存。

3. JS 端优化

  • 减少 DOM 操作,用 DocumentFragment 批量插入。
  • 避免频繁 evaluateJavaScript,合并多次调用。
  • 大图懒加载、CSS 动画用 transform/opacity(触发 GPU 合成,不重排)。

4. 内存优化

  • 页面消失时调用 stopLoading 并移除代理。
  • 及时 removeScriptMessageHandlerForName: 避免循环引用。
  • 长时间运行的 WebView 可定期 reload 释放 Web 进程累积内存。

六、OC 与 JS 通信(四种传参方式)

1. URL Scheme(初始加载传参)

适合页面初始加载时传递数据,将参数拼接到 URL query 中:

NSString *urlString = [NSString stringWithFormat:@"https://example.com?userId=%@&token=%@", @"12345", @"abc"];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
// JS 端获取
const params = new URLSearchParams(window.location.search);
const userId = params.get("userId");

2. evaluateJavaScript(OC 主动调 JS)

页面加载后随时传递数据,灵活但需注意参数转义:

// 简单参数(需转义特殊字符:单引号、换行、反斜杠)
NSString *userId = @"12345";
NSString *userName = @"John'Doe"; // 含单引号需转义
NSString *escapedName = [userName stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
NSString *js = [NSString stringWithFormat:@"setUserInfo('%@', '%@');", userId, escapedName];

[self.webView evaluateJavaScript:js completionHandler:^(id result, NSError *error) {
    if (error) NSLog(@"JS 错误: %@", error);
}];

安全提示:直接拼接 JS 字符串有注入风险,参数中的单引号、双引号、换行、反斜杠必须转义。传递复杂数据建议用 WKScriptMessageHandler(JS 调 OC)或 JSON 序列化后传递。

3. WKUserScript(页面加载前注入)

在页面加载的指定时机(文档开始/结束)自动注入 JS 代码,适合初始化全局数据:

NSString *scriptSource = @"window.userInfo = {userId: '12345', userName: 'John'};";

// injectionTime: 文档开始时注入(DOM 解析前)
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:scriptSource
                                                     injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                                  forMainFrameOnly:YES];

WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addUserScript:userScript];
injectionTime 说明
WKUserScriptInjectionTimeAtDocumentStart 文档开始时注入(DOM 解析前,所有 JS 执行前)
WKUserScriptInjectionTimeAtDocumentEnd 文档加载完成后注入(DOMContentLoaded 后)

4. Document.cookie(不推荐)

通过设置 cookie 传递数据,不推荐用于敏感信息:

NSString *js = @"document.cookie = 'userId=12345; path=/';";
[self.webView evaluateJavaScript:js completionHandler:nil];

方式选择

方式 时机 适用场景
URL Scheme 初始加载 页面初始化参数(token、用户 ID)
evaluateJavaScript 加载后随时 OC 主动调用 JS 函数、传参
WKUserScript 加载前/后自动注入 全局数据初始化、JS 环境配置
Document.cookie 随时 不推荐,仅兼容旧页面
WKScriptMessageHandler JS 主动调 OC JS 向原生发送消息、事件通知

七、跨平台方案

1. React Native (RN)

原理:JavaScript 线程 + 原生组件映射。

  • 业务逻辑用 JavaScript(或 TypeScript)编写,运行在独立的 JS 线程中(iOS 上用 JavaScriptCore 或 JSC,新架构用 Hermes)。
  • JS 线程通过 Bridge(异步序列化消息)与原生线程通信,JS 描述 UI 结构(如 <View>、<Text>),原生端映射为真实的 UIView/UILabel 等原生组件进行渲染。
  • 渲染用原生组件,不是 WebView,因此性能接近原生 App。
  • 新架构(Fabric + TurboModules + JSI)优化了 Bridge 通信开销,支持同步调用和并发渲染。

特点:一套代码多端运行(iOS/Android),UI 用原生组件渲染,性能较好;JS 与原生通信有 Bridge 开销。

2. Flutter

原理:Dart 语言 + Skia 自绘引擎。

  • 业务逻辑和 UI 都用 Dart 编写,AOT(Ahead Of Time)编译为原生机器码(iOS 上编译为 ARM 机器码)。
  • 不依赖原生组件,Flutter 自带 Skia 2D 渲染引擎(iOS 上用 Metal/OpenGL 后端),自己绘制所有 UI 元素(按钮、文本、列表等),不映射到 UIView。
  • 渲染性能高且跨端一致性好(同一套渲染引擎,iOS/Android 显示完全一致)。
  • Dart 虚拟机支持热重载(Hot Reload),开发效率高。

特点:性能最接近原生(自绘引擎,无 Bridge 开销),跨端一致性最好;包体积较大(需打包 Skia 引擎和 Dart 运行时),生态小于 RN。

3. Weex / uni-app

原理:类似 RN,JS 驱动原生组件。

  • Weex 用 Vue 语法编写,JS 描述 UI,原生端映射为原生组件渲染。
  • uni-app 基于 Vue,支持编译到多端(iOS/Android/小程序/H5),App 端原理类似 Weex(JS + 原生组件),小程序端编译为小程序代码。
  • 相比 RN,更偏向国内生态和小程序多端统一。

4. Cordova / PhoneGap(WebView 套壳)

原理:WebView + JS Bridge。

  • 整个 App 界面就是一个全屏 WKWebView(或 UIWebView),加载本地 H5 页面(HTML/CSS/JS)。
  • H5 通过 JS Bridge(拦截 URL scheme 或 WKScriptMessageHandler)调用原生能力(相机、定位、文件等),原生将结果回调给 JS。
  • 本质是网页套壳,UI 由 WebView 渲染,性能不如原生和 RN/Flutter,但开发成本最低(纯前端技术栈)。

特点:开发成本最低(H5 技术栈),性能最差(WebView 渲染),适合简单内容型 App。

5. 小程序

原理:双线程模型 + JSBridge。

  • 逻辑层:独立的 JS 线程(iOS 上用 JavaScriptCore),运行小程序业务逻辑(JS),不能直接操作 DOM。
  • 渲染层:WebView(或原生渲染),负责 UI 渲染,接收逻辑层传来的数据更新界面。
  • 两层通过 JSBridge / 原生桥 通信(setData 传递数据、事件通知),数据通过序列化传递。
  • 双线程隔离保证安全(逻辑层无法直接操作渲染层 DOM),但通信有开销,频繁 setData 会卡顿。

特点:双线程隔离,安全可控;渲染层可用 WebView 或原生组件(如微信小程序的 Skyline 渲染引擎);依赖宿主 App(微信/支付宝等)运行。

6. 跨平台方案对比

方案 语言 渲染方式 性能 跨端一致性 开发成本 代表
原生 Swift/OC, Kotlin/Java 原生组件 最高 差(各端独立) 最高 iOS/Android 原生
Flutter Dart Skia 自绘 接近原生 最好 中 闲鱼、美团
React Native JS/TS 原生组件映射 较好 较好 中 Facebook、Shopify
Weex/uni-app Vue 原生组件映射 较好 较好 中低 淘宝、京东
小程序 JS WebView/原生 中等 好(同平台内) 低 微信/支付宝小程序
Cordova H5 WebView 套壳 最差 好 最低 简单内容 App

与 WKWebView 的关系:Cordova 和小程序的渲染层本质都依赖 WebView(WKWebView),通过 JSBridge 与原生通信;RN 和 Flutter 不使用 WebView,RN 用原生组件、Flutter 用 Skia 自绘。WKWebView 是跨平台方案中 Web 渲染路线的基础组件。


八、Swift 版本对照

WKWebView 基本使用(Swift)

import WebKit

class WebViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
    var webView: WKWebView!
    var progressView: UIProgressView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let config = WKWebViewConfiguration()
        config.userContentController.add(self, name: "nativeHandler")
        
        webView = WKWebView(frame: view.bounds, configuration: config)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        view.addSubview(webView)
        
        // KVO 进度
        webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
        
        webView.load(URLRequest(url: URL(string: "https://www.apple.com")!))
    }
    
    // MARK: - WKNavigationDelegate
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("加载完成")
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url?.absoluteString, url.hasPrefix("customscheme://") {
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }
    
    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        webView.reload()
    }
    
    // MARK: - WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "nativeHandler" {
            print("JS 消息: \(message.body)")
        }
    }
    
    // OC 调 JS
    func callJS() {
        webView.evaluateJavaScript("document.title") { result, error in
            if let title = result as? String {
                print("标题: \(title)")
            }
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(WKWebView.estimatedProgress) {
            progressView.progress = Float(webView.estimatedProgress)
        }
    }
    
    deinit {
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "nativeHandler")
        webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
    }
}

九、总结

  • WKWebView 架构:多进程(UI 进程 + Web 内容进程 + 网络进程),通过 XPC 通信;Web 进程崩溃不影响 App,Nitro JS 引擎支持 JIT,性能远高于 UIWebView;iOS 12 起 UIWebView 废弃,WKWebView 是唯一推荐。
  • 基本使用:WKWebViewConfiguration 配置后初始化,四种加载方式(loadRequest/loadHTMLString/loadData/loadFileURL),导航控制(reload/reloadFromOrigin/goBack/goForward/stopLoading),OC 调 JS 用异步的 evaluateJavaScript:completionHandler:。
  • 代理:WKNavigationDelegate 管理加载过程(开始/完成/失败/进程崩溃/拦截请求响应/HTTPS 认证),decidePolicy 必须调用 decisionHandler;WKUIDelegate 处理 JS 三面板(alert/confirm/prompt,必须调用 completionHandler)、新窗口、文件上传。
  • JS 交互:WKScriptMessageHandler 实现 JS 调 OC(window.webkit.messageHandlers.<name>.postMessage()),addScriptMessageHandler 强引用 delegate 导致循环引用,dealloc 前必须 removeScriptMessageHandlerForName:。
  • 进度与标题:KVO 监听 estimatedProgress(0~1)和 title 属性。
  • 性能优化:WKWebView 有独立 Network Cache,NSURLCache 影响有限,缓存主要由服务器响应头控制;提前初始化/复用 WKWebView、共享 WKProcessPool 降低进程开销;JS 端减少 DOM 操作和频繁 evaluateJavaScript。
  • OC 与 JS 传参:URL Scheme(初始加载)、evaluateJavaScript(加载后随时,注意参数转义)、WKUserScript(加载前/后自动注入,AtDocumentStart/AtDocumentEnd)、Document.cookie(不推荐);JS 调 OC 用 WKScriptMessageHandler。
  • 跨平台方案:Flutter(Dart + Skia 自绘,性能最接近原生)、RN(JS + 原生组件映射 + Bridge)、Weex/uni-app(Vue + 原生组件)、Cordova(WebView 套壳 + JSBridge,性能最差)、小程序(双线程模型 + JSBridge);Cordova 和小程序渲染层依赖 WKWebView,RN/Flutter 不使用 WebView。

posted @ 2024-08-03 18:28  Mr.陳  阅读(1744)  评论(0)    收藏  举报