我們做項目的時候會避免不了使用WebView之類的滾動視圖,之前一直在使用UIWebView。但UIWebView存在加載速度慢、佔用內存大等問題,後來蘋果在iOS8.0之後推出了WKWebView,增加了更多強大的功能,提供了豐富的接口。
1).下面主要說一下在使用WKWebView實現oc與js之間相互傳值的功能實現:
首先引入<WebKit/WebKit.h>框架
#import <WebKit/WebKit.h>
下面是我要演示的html中需要調用的js代碼
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<script language="javascript">
//1.返回
function backClick() {
window.webkit.messageHandlers.Back.postMessage(null);
}
//2.修改背景色
function colorClick() {
window.webkit.messageHandlers.Color.postMessage(null);
}
//3.js傳參數
function paramClick() {
var content = document.getElementById("firstid").value;
window.webkit.messageHandlers.Param.postMessage({first:'來自js的數據:',second:content});
}
//展示oc所傳js數據
function transferPrama(str) {
asyncAlert(str);//響應WKUIDelegate的代理方法runJavaScriptAlertPanelWithMessage
document.getElementById("secondid").value = str;
}
function asyncAlert(content) {
setTimeout(function() {
alert(content);
},1);
}
</script>
</head>
然後新建webView,配置參數和屬性
- (WKWebView *)webView {
if (!_webView) {
//配置控制器
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = [WKUserContentController new];
//配置js調用統一參數
[configuration.userContentController addScriptMessageHandler:self name:@"Back"];
[configuration.userContentController addScriptMessageHandler:self name:@"Color"];
[configuration.userContentController addScriptMessageHandler:self name:@"Param"];
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
preferences.minimumFontSize = 40.0;
configuration.preferences = preferences;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, K_ScreenWidth, K_ScreenWidth*5/4-20) configuration:configuration];
_webView.UIDelegate = self;
NSString * urlStr = [[NSBundle mainBundle] pathForResource:@"wkwebview.html" ofType:nil];
NSURL * fileURL = [NSURL fileURLWithPath:urlStr];
[_webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
}
return _webView;
}
其中以下三個參數的配置是和js代碼中的函數調用相對應的
//配置js調用統一參數
[configuration.userContentController addScriptMessageHandler:self name:@"Back"];
[configuration.userContentController addScriptMessageHandler:self name:@"Color"];
[configuration.userContentController addScriptMessageHandler:self name:@"Param"];
添加代理WKUIDelegate和WKScriptMessageHandler
<WKUIDelegate,WKScriptMessageHandler>
實現對應代理方法
WKUIDelegate代理方法:
#pragma mark - WKUIDelegate
// 在JS端調用alert函數alert(content)時,會觸發此代理方法,通過message可以拿到JS端所傳的數據,在iOS端得到結果後,需要回調JS,通過completionHandler回調給JS端
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"JS調用alert" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:nil];
}
// 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 {
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];
}
//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__);
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];
}
以上三個代理方法分別會在JS端調用alert函數、confirm函數以及prompt函數時,分別觸發對應的方法。
WKScriptMessageHandler代理方法:
#pragma mark - WKScriptMessageHandler
//接收從js傳給oc的數據
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"Back"]) {
[self.navigationController popViewControllerAnimated:YES];
} else if ([message.name isEqualToString:@"Color"]) {
[self changeBackGroundViewColor];
} else if ([message.name isEqualToString:@"Param"]) {
[self jsParams:message.body];
}
}
上面代理方法是用來接收從js傳給oc的數據,其中(WKScriptMessage *)message 的name屬性用於對應在js代碼中設置的參數,body是接收的傳過來的數據。
//oc數據傳給js
- (void)transterClick {
NSString * paramString = self.OCView.fieldView.text;
//transferPrama()是JS的語言
NSString * jsStr = [NSString stringWithFormat:@"transferPrama('%@')",paramString];
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"result=%@ error=%@",result, error);
}];
}
上面方法是用來將oc數據傳給js,其中transferPrama()是js的語言,是js代碼中用來接受oc數據的方法,其中參數str是oc傳過去的數據,js接收方法如下:
//展示oc所傳js數據
function transferPrama(str) {
document.getElementById("secondid").value = str;
}
2).下面說一下WKWebView的WKNavigationDelegate代理方法:
在上面的基礎上添加代理WKNavigationDelegate
<WKNavigationDelegate>
設置代理:
_webView.navigationDelegate = self;
對應代理方法
WKUIDelegate代理方法:
#pragma mark - WKNavigationDelegate
/**
//如果不實現這個方法,web視圖將加載請求,或在適當的情況下,其轉發到另一個應用程序。(在發送請求之前,決定是否跳轉)
- (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__);
}
*/
/**
//如果不實現這個方法,將允許響應web視圖,如果web視圖可以表現出來。(在收到響應後,決定是否跳轉)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
// 如果響應的地址是百度,則允許跳轉
if ([navigationResponse.response.URL.host.lowercaseString isEqual:@"www.baidu.com"]) {
// 允許跳轉
decisionHandler(WKNavigationResponsePolicyAllow);
return;
}
// 不允許跳轉
decisionHandler(WKNavigationResponsePolicyCancel);
}
*/
//開始調用一個主框架導航(頁面開始加載時調用)
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
}
//調用的主要服務器接收到重定向框架(接收到服務器跳轉請求之後調用)
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
}
//開始加載數據時出現錯誤時調用(加載失敗時調用)
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}
//內容開始到達時調用的主要框架(當內容開始返回時調用)
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
}
//主框架導航完成時調用(頁面加載完成之後調用)
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
}
//發生錯誤時調用(導航失敗時會回調)
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}
/**
//討論如果你不實現這個方法,web視圖將響應身份驗證的挑戰,對於HTTPS的都會觸發此代理,如果不要求驗證,傳默認就行,如果需要證書驗證,與使用AFN進行HTTPS證書驗證是一樣的
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
*/
//調用web視圖的web內容過程終止時調用,9.0才能使用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0)) {
}
設置WKWebView加載進度條:
添加屬性:
@property(nonatomic,strong)UIProgressView * progressView;
創建UIProgressView:
- (UIProgressView *)progressView {
if (!_progressView) {
_progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
_progressView.frame = CGRectMake(0, 0, K_ScreenWidth, 2.5);
_progressView.tintColor = [UIColor blueColor];
_progressView.trackTintColor = [UIColor lightGrayColor];
}
return _progressView;
}
_webView添加監聽(記得退出時銷燬):
#define k_estimatedProgress @"estimatedProgress"
[_webView addObserver:self forKeyPath:k_estimatedProgress options:NSKeyValueObservingOptionNew context:nil];
實現監聽方法:
#pragma mark - KVO
//計算WKWebView進度條
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == self.webView && [keyPath isEqualToString:k_estimatedProgress]) {
CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
if (newprogress == 1) {
[self.progressView setProgress:1.0 animated:YES];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progressView.hidden = YES;
[self.progressView setProgress:0 animated:NO];
});
}else {
self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
}
}
}
Demo地址:WKWebView與js交互及代理方法
「歡迎指正交流」0_0