WKWebView 是蘋(píng)果在 iOS 8 中引入的新組件帚称,目的是給出一個(gè)新的高性能的 Web View 解決方案官研,擺脫過(guò)去 UIWebView 的老舊笨重特別是內(nèi)存占用量巨大的問(wèn)題。它的優(yōu)點(diǎn)在于占用更少的內(nèi)存闯睹,處理速度更快戏羽。不過(guò)有點(diǎn)一點(diǎn)不像webview每次打開(kāi)網(wǎng)頁(yè)沒(méi)有緩存,如果用戶要配置一些個(gè)人的信息在請(qǐng)求里面楼吃,需要配置:
WKWebViewConfiguration 這個(gè)類始花。
js交互
<p></p><pre><code>
// js配置
WKWebViewConfiguration*config=[[WKWebViewConfiguration alloc] init];
// 設(shè)置偏好設(shè)置
config.preferences = [[WKPreferences alloc] init];
// 默認(rèn)為0
config.preferences.minimumFontSize = 10;
// 默認(rèn)認(rèn)為YES
config.preferences.javaScriptEnabled = YES;
// 在iOS上默認(rèn)為NO,表示不能自動(dòng)通過(guò)窗口打開(kāi)
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
config.userContentController = [[WKUserContentController alloc] init];
// 注入JS對(duì)象名稱AppModel孩锡,當(dāng)JS通過(guò)AppModel來(lái)調(diào)用時(shí)酷宵,
// 我們可以在WKScriptMessageHandler代理中接收到
[config.userContentController addScriptMessageHandler:self name:@"MModel"];
_wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
</code></pre>
進(jìn)度條
<p></p><pre><code>
// 計(jì)算wkWebView進(jìn)度條
-
(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if (_isLoad) {
return;
}if ([keyPath isEqualToString:@"estimatedProgress"]) {
self.progresslayer.opacity = 1;
CGFloat new = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
CGFloat old = [[change objectForKey:NSKeyValueChangeOldKey] doubleValue];
if (new < old) {
return;
}
self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
if ([change[@"new"] floatValue] == 1) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.opacity = 0;
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
});
}
}
}
</code></pre>
刷新
<p></p><pre><code>
// 增加拉刷新
MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(onHeader)];
[header setTitle:@"下拉刷新" forState:MJRefreshStatePulling];
header.lastUpdatedTimeLabel.hidden = YES;
_wkWebView.scrollView.mj_header = header;
</code></pre>
左右滑動(dòng)
<p></p><pre><code>
// 瀏覽器內(nèi)左右滑動(dòng)
_wkWebView.allowsBackForwardNavigationGestures = YES;
</code></pre>