OC 與 html 的交互的使用

通過本篇文章,至少可以學(xué)習(xí)到:

OC如何給JS注入對象及JS如何給IOS發(fā)送數(shù)據(jù)

JS調(diào)用alert、confirm、prompt時,不采用JS原生提示,而是使用iOS原生來實現(xiàn)

如何監(jiān)聽web內(nèi)容加載進度、是否加載完成

如何處理去跨域問題


創(chuàng)建配置類

在創(chuàng)建WKWebView之前,需要先創(chuàng)建配置對象,用于做一些配置:

WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

配置偏好設(shè)置

偏好設(shè)置也沒有必須去修改它,都使用默認的就可以了,除非你真的需要修改它:

// 設(shè)置偏好設(shè)置

config.preferences = [[WKPreferences alloc] init];

// 默認為0

config.preferences.minimumFontSize = 10;

// 默認認為YES

config.preferences.javaScriptEnabled = YES;

// 在iOS上默認為NO,表示不能自動通過窗口打開

config.preferences.javaScriptCanOpenWindowsAutomatically = NO;

配置web內(nèi)容處理池

其實我們沒有必要去創(chuàng)建它,因為它根本沒有屬性和方法:

// web內(nèi)容處理池,由于沒有屬性可以設(shè)置,也沒有方法可以調(diào)用,不用手動創(chuàng)建

config.processPool = [[WKProcessPool alloc] init];

配置Js與Web內(nèi)容交互

WKUserContentController是用于給JS注入對象的,注入對象后,JS端就可以使用:

window.webkit.messageHandlers..postMessage

(來調(diào)用發(fā)送數(shù)據(jù)給iOS端,比如:window.webkit.messageHandlers.AppModel.postMessage({body: '傳數(shù)據(jù)'});

AppModel就是我們要注入的名稱,注入以后,就可以在JS端調(diào)用了,傳數(shù)據(jù)統(tǒng)一通過body傳,可以是多種類型,只支持NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull類型。

下面我們配置給JS的main frame注入AppModel名稱,對于JS端可就是對象了

// 通過JS與webview內(nèi)容交互

config.userContentController = [[WKUserContentController alloc] init];

// 注入JS對象名稱AppModel,當JS通過AppModel來調(diào)用時,

// 我們可以在WKScriptMessageHandler代理中接收到

[config.userContentController addScriptMessageHandler:self name:@"AppModel"];

當JS通過AppModel發(fā)送數(shù)據(jù)到iOS端時,會在代理中收到:

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController

didReceiveScriptMessage:(WKScriptMessage *)message {

if ([message.name isEqualToString:@"AppModel"]) {

// 打印所傳過來的參數(shù),只支持NSNumber, NSString, NSDate, NSArray,

// NSDictionary, and NSNull類型

NSLog(@"%@", message.body);

}

}

所有JS調(diào)用iOS的部分,都只可以在此處使用哦。當然我們也可以注入多個名稱(JS對象),用于區(qū)分功能。

創(chuàng)建WKWebView

通過唯一的默認構(gòu)造器來創(chuàng)建對象:

5self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds

configuration:config];

[self.view addSubview:self.webView];

加載H5頁面

NSURL *path = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];

[self.webView loadRequest:[NSURLRequest requestWithURL:path]];

配置代理

如果需要處理web導(dǎo)航條上的代理處理,比如鏈接是否可以跳轉(zhuǎn)或者如何跳轉(zhuǎn),需要設(shè)置代理;而如果需要與在JS調(diào)用alert、confirm、prompt函數(shù)時,通過JS原生來處理,而不是調(diào)用JS的alert、confirm、prompt函數(shù),那么需要設(shè)置UIDelegate,在得到響應(yīng)后可以將結(jié)果反饋到JS端:

// 導(dǎo)航代理

self.webView.navigationDelegate = self;

// 與webview UI交互代理

self.webView.UIDelegate = self;

添加對WKWebView屬性的監(jiān)聽

WKWebView有好多個支持KVO的屬性,這里只是監(jiān)聽loading、title、estimatedProgress屬性,分別用于判斷是否正在加載、獲取頁面標題、當前頁面載入進度:

// 添加KVO監(jiān)聽

[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];

然后我們就可以實現(xiàn)KVO處理方法,在loading完成時,可以注入一些JS到web中。這里只是簡單地執(zhí)行一段web中的JS函數(shù):

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath

ofObject:(id)object

change:(NSDictionary *)change

context:(void *)context {

if ([keyPath isEqualToString:@"loading"]) {

NSLog(@"loading");

} else if ([keyPath isEqualToString:@"title"]) {

self.title = self.webView.title;

} else if ([keyPath isEqualToString:@"estimatedProgress"]) {

NSLog(@"progress: %f", self.webView.estimatedProgress);

self.progressView.progress = self.webView.estimatedProgress;

}

// 加載完成

if (!self.webView.loading) {

// 手動調(diào)用JS代碼

// 每次頁面完成都彈出來,大家可以在測試時再打開

NSString *js = @"callJsAlert()";

[self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {

NSLog(@"response: %@ error: %@", response, error);

NSLog(@"call js alert by native");

}];

[UIView animateWithDuration:0.5 animations:^{

self.progressView.alpha = 0;

}];

}

}

WKUIDelegate

與JS原生的alert、confirm、prompt交互,將彈出來的實際上是我們原生的窗口,而不是JS的。在得到數(shù)據(jù)后,由原生傳回到JS:

#pragma mark - WKUIDelegate

- (void)webViewDidClose:(WKWebView *)webView {

NSLog(@"%s", __FUNCTION__);

}

// 在JS端調(diào)用alert函數(shù)時,會觸發(fā)此代理方法。

// JS端調(diào)用alert時所傳的數(shù)據(jù)可以通過message拿到

// 在原生得到結(jié)果后,需要回調(diào)JS,是通過completionHandler回調(diào)

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {

NSLog(@"%s", __FUNCTION__);

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS調(diào)用alert" preferredStyle:UIAlertControllerStyleAlert];

[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

completionHandler();

}]];

[self presentViewController:alert animated:YES completion:NULL];

NSLog(@"%@", message);

}

// JS端調(diào)用confirm函數(shù)時,會觸發(fā)此方法

// 通過message可以拿到JS端所傳的數(shù)據(jù)

// 在iOS端顯示原生alert得到Y(jié)ES/NO后

// 通過completionHandler回調(diào)給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調(diào)用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端調(diào)用prompt函數(shù)時,會觸發(fā)此方法

// 要求輸入一段文本

// 在原生輸入得到文本內(nèi)容后,通過completionHandler回調(diào)給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調(diào)用輸入框" 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];

}

WKNavigationDelegate

如果需要處理web導(dǎo)航操作,比如鏈接跳轉(zhuǎn)、接收響應(yīng)、在導(dǎo)航開始、成功、失敗等時要做些處理,就可以通過實現(xiàn)相關(guān)的代理方法:

#pragma mark - WKNavigationDelegate

// 請求開始前,會先調(diào)用此代理方法

// 與UIWebView的

// - (BOOL)webView:(UIWebView *)webView

// shouldStartLoadWithRequest:(NSURLRequest *)request

// navigationType:(UIWebViewNavigationType)navigationType;

// 類型,在請求先判斷能不能跳轉(zhuǎn)(請求)

- (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"]) {

// 對于跨域,需要手動跳轉(zhuǎn)

[[UIApplication sharedApplication] openURL:navigationAction.request.URL];

// 不允許web內(nèi)跳轉(zhuǎn)

decisionHandler(WKNavigationActionPolicyCancel);

} else {

self.progressView.alpha = 1.0;

decisionHandler(WKNavigationActionPolicyAllow);

}

NSLog(@"%s", __FUNCTION__);

}

// 在響應(yīng)完成時,會回調(diào)此方法

// 如果設(shè)置為不允許響應(yīng),web內(nèi)容就不會傳過來

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {

decisionHandler(WKNavigationResponsePolicyAllow);

NSLog(@"%s", __FUNCTION__);

}

// 開始導(dǎo)航跳轉(zhuǎn)時會回調(diào)

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {

NSLog(@"%s", __FUNCTION__);

}

// 接收到重定向時會回調(diào)

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {

NSLog(@"%s", __FUNCTION__);

}

// 導(dǎo)航失敗時會回調(diào)

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {

NSLog(@"%s", __FUNCTION__);

}

// 頁面內(nèi)容到達main frame時回調(diào)

- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {

NSLog(@"%s", __FUNCTION__);

}

// 導(dǎo)航完成時,會回調(diào)(也就是頁面載入完成了)

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {

NSLog(@"%s", __FUNCTION__);

}

// 導(dǎo)航失敗時會回調(diào)

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {

}

// 對于HTTPS的都會觸發(fā)此代理,如果不要求驗證,傳默認就行

// 如果需要證書驗證,與使用AFN進行HTTPS證書驗證是一樣的

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler {

NSLog(@"%s", __FUNCTION__);

completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);

}

// 9.0才能使用,web內(nèi)容處理中斷時會觸發(fā)

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {

NSLog(@"%s", __FUNCTION__);

}

JS端代碼

demo? 鏈接 https://github.com/CoderJackyHuang/WKWebViewH5ObjCDemo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容