從 UIWebView 到 WKWebView

WKWebView 是 iOS 8 引入的一個 WebKit API,替換 iOS 的 UIWebView 和 OSX 的 WebView,WKWebView 使用 Nitro JavaScript 引擎,運行 JavaScript 和 Safari 一樣快。WKWebView 和 UIWebView 使用上有很多區別,這篇主要介紹代理、標題、進度條展示的區別。

代理

UIWebView 是 delegate: 'UIWebViewDelegate',WKWebView 使用以下兩個代理

navigationDelegate: ' WKNavigationDelegate'
UIDelegate: ' WKUIDelegate'

其中 navigationDelegate 代替 UIWebView 中的 delegate,下表是這兩個代理方法的對比:

這裏寫圖片描述

比如,如果要攔截網頁請求,UIWebView 使用以下代碼:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
     NSURL *url = request.URL;
    NSString *host = [url host];
    if ([url.scheme isEqualToString:@"inapp"]) {

        /*
         * 做一些處理
         */

        return NO;
    }

    return YES;
}

在 WKWebView 中則用以下代碼:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    NSURL *url = navigationAction.request.URL;
    NSString *host = [url host];
    if ([url.scheme isEqualToString:@"inapp"]) {

        /*
         * 做一些處理
         */

        decisionHandler(WKNavigationActionPolicyCancel);
    } else {

        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

獲取 title

在 UIWebView 中

self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

而 WKWebView 有 title 屬性可直接獲取網頁標題,可通過 KVO 方式獲取網頁標題的動態變化。

self.title = webView.title;
estimatedProgress

WKWebView 增加了 estimatedProgress,獲取網頁加載進度,輕鬆顯示進度條。可通過 KVO 的方式獲取 estimatedProgress 的變化。首先在 viewDidLoad 中添加觀察者

[self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:NSKeyValueObservingOptionNew context:NULL];
[self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(title)) options:NSKeyValueObservingOptionNew context:NULL];

KVO 的實現:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
        NSLog(@"%f", self.webView.estimatedProgress);
        // estimatedProgress is a value from 0.0 to 1.0
        // Update your UI here accordingly

        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];

        if(self.webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }

    } else if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
            self.title = self.webView.title;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else {

        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

最後,在 dealloc 中移除觀察者

- (void)dealloc {
    if ([self isViewLoaded]) {
        [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
        [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(title))];
    }

    [self.webView setNavigationDelegate:nil];
}

WKWebView 還增加了 Message Handlers,用於和網頁的JS交互,不需要處理複雜的evaluateJavaScript。例如:

class NotificationScriptMessageHandler: NSObject, WKScriptMessageHandler {
    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage!) {
        print(message.body)
    }
}

let userContentController = WKUserContentController()
let handler = NotificationScriptMessageHandler()
userContentController.addScriptMessageHandler(handler, name: "notification")

則 JavaScript 端可通過以下代碼即可調用原生的代碼:

window.webkit.messageHandlers.notification.postMessage({body: "..."});

轉自:簡書作者蝦米233

詳情參考 NSHipster 這篇 WKWeb​View

發佈了203 篇原創文章 · 獲贊 73 · 訪問量 76萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章