iOS 8引入了一個新的框架——WebKit,之后變得好起來了。在WebKit框架中,有WKWebView可以替換UIKit的UIWebView和AppKit的WebView,而且提供了在兩個平台可以一致使用的接口。 WebKit框架使得開發者可以在原生App中使用Nitro來提高網頁的性能和表現,Nitro就是Safari的JavaScript引擎。
下面舉個🌰
代碼中有詳細的注釋
// // ViewController.m // WKWebView01 // // Created by njdby on 16/7/8. // Copyright © 2016年 njdby. All rights reserved. // #import "ViewController.h" #import <WebKit/WebKit.h> @interface ViewController ()<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler> @property (nonatomic, strong) WKWebView *webView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; // 設置偏好設置 config.preferences = [[WKPreferences alloc] init]; // 默認為0 config.preferences.minimumFontSize = 10; // 默認認為YES config.preferences.javaScriptEnabled = YES; // 在iOS上默認為NO,表示不能自動通過窗口打開 config.preferences.javaScriptCanOpenWindowsAutomatically = NO; // web內容處理池,由於沒有屬性可以設置,也沒有方法可以調用,不用手動創建 config.processPool = [[WKProcessPool alloc] init]; // 通過JS與webview內容交互 config.userContentController = [[WKUserContentController alloc] init]; // 注入JS對象名稱AppModel,當JS通過AppModel來調用時, // 我們可以在WKScriptMessageHandler代理中接收到 [config.userContentController addScriptMessageHandler:self name:@"AppModel"]; self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; [self.view addSubview:self.webView]; // 導航代理 self.webView.navigationDelegate = self; // 與webview UI交互代理 self.webView.UIDelegate = self; // [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]]; NSURL *path = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"]; [self.webView loadRequest:[NSURLRequest requestWithURL:path]]; // 添加KVO監聽 [self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; } #pragma mark - WKUIDelegate #if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_9_0 - (void)webViewDidClose:(WKWebView *)webView { NSLog(@"%s", __FUNCTION__); } #endif // 創建一個新的WebView(標簽帶有 target='_blank' 時,導致WKWebView無法加載點擊后的網頁的問題。) - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { // 接口的作用是打開新窗口委托 WKFrameInfo *frameInfo = navigationAction.targetFrame; if (![frameInfo isMainFrame]) { [webView loadRequest:navigationAction.request]; } return nil; } // 在JS端調用alert函數時,會觸發此代理方法。 // JS端調用alert時所傳的數據可以通過message拿到 // 在原生得到結果后,需要回調JS,是通過completionHandler回調 - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler { NSLog(@"%s", __FUNCTION__); UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS調用alert" preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler(); }]]; [self presentViewController:alert animated:YES completion:NULL]; NSLog(@"%@", message); } // JS端調用confirm函數時,會觸發此方法 // 通過message可以拿到JS端所傳的數據 // 在iOS端顯示原生alert得到YES/NO后 // 通過completionHandler回調給JS端 - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler { NSLog(@"%s", __FUNCTION__); UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS調用confirm" 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:NULL]; NSLog(@"%@", message); } // JS端調用prompt函數時,會觸發此方法 // 要求輸入一段文本 // 在原生輸入得到文本內容后,通過completionHandler回調給JS - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler { NSLog(@"%s", __FUNCTION__); NSLog(@"%@", prompt); UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS調用輸入框" preferredStyle:UIAlertControllerStyleAlert]; [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.textColor = [UIColor redColor]; }]; [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler([[alert.textFields lastObject] text]); }]]; [self presentViewController:alert animated:YES completion:NULL]; } #pragma mark - WKNavigationDelegate #pragma mark - WKNavigationDelegate /** * 在發送請求之前,決定是否跳轉 * * @param webView 實現該代理的 * @param navigationAction 當前navigation * @param decisionHandler 是否調轉block */ - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSString *hostname = navigationAction.request.URL.host.lowercaseString; if (navigationAction.navigationType == WKNavigationTypeLinkActivated && ![hostname containsString:@".baidu.com"]) { // 對於跨域,需要手動跳轉 [[UIApplication sharedApplication] openURL:navigationAction.request.URL]; // 不允許web內跳轉 decisionHandler(WKNavigationActionPolicyCancel); } else { self.progressView.alpha = 1.0; decisionHandler(WKNavigationActionPolicyAllow); } NSLog(@"%s", __FUNCTION__); } /** * 在收到響應后,決定是否跳轉 * * @param webView 實現該代理的webview * @param navigationResponse 當前navigation * @param decisionHandler 是否跳轉block */ - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { // NSLog(@"%@",navigationResponse.response); // 如果響應的地址是百度,則允許跳轉 // if ([navigationResponse.response.URL.host.lowercaseString isEqual:@"www.baidu.com"]) { // // // 允許跳轉 // decisionHandler(WKNavigationResponsePolicyAllow); // return; // } // // 不允許跳轉 // decisionHandler(WKNavigationResponsePolicyCancel); decisionHandler(WKNavigationResponsePolicyAllow); } /** * 頁面開始加載時調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation */ - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"%s", __FUNCTION__); } /** * 接收到服務器跳轉請求之后調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation */ - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"%s", __FUNCTION__); } /** * 加載失敗時調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation * @param error 錯誤 */ - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { NSLog(@"%s", __FUNCTION__); } /** * 當內容開始返回時調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation */ - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"%s", __FUNCTION__); } /** * 頁面加載完成之后調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation */ - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { 