iOS wkwebview 載入html
阿新 • • 發佈:2018-11-28
wkwebview的優勢
1.互動更方便
2.更低的記憶體佔用
3.高達60fps的滾動重新整理率以及內建手勢
4.支援更多的HTML5特性
5.基於webkit核心,支援Nitro JavaScript引擎
6.提供常用的屬性,如載入網頁進度的屬性estimatedProgress
wkwebview的使用
首先需要引入標頭檔案
#import <WebKit/WebKit.h>
js呼叫oc
配置configuration
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init]; //註冊方法 [configuration.userContentController addScriptMessageHandler:self name:@"方法名"]; _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) configuration:configuration]; _webView.UIDelegate = self; _webView.navigationDelegate = self; _webView.scrollView.bounces = NO;
實現協議:
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ NSLog(@" NSStringFromSelector(_cmd) == %@ \n",NSStringFromSelector(_cmd)); NSLog(@"message.body%@ \n name:%@",message.body,message.name); if ([message.name isEqualToString:@"方法名"]) { }else { } }
js呼叫oc,html5寫法:window.webkit.messageHandlers.方法名.postMessage(引數)
oc呼叫js:
NSString *js = @"name('引數')";
[self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"response:%@..error:%@",response,error);
}];
wkwebview使用時遇到的問題
用wkwebview載入本地html(如果把下砸的html檔案放到沙盒裡)的時候會出現,載入不了圖片的問題,這是因為沙盒的安全機制,使用Apple提供的另外一個API使用者訪問本地檔案:
[self.webView loadFileURL:[NSURL fileURLWithPath:filePath] allowingReadAccessToURL:baseURL];
其中:
- filePath是需要顯示的檔案路徑,這個目錄指的是HTML的檔案路徑。
- baseURL是需要訪問的相關檔案的目錄。這個目錄包括HTML檔案本身和用到的資源,比如圖片等。