簡(jiǎn)單說(shuō)說(shuō)iOS之WKWebView的用法小結(jié)
WKWebView的優(yōu)勢(shì)
- 性能高,穩(wěn)定性好,占用的內(nèi)存比較小,
- 支持JS交互
- 支持HTML5 新特性
- 可以添加進(jìn)度條(不好用,還是習(xí)慣第三方的)。
- 支持內(nèi)建手勢(shì),
- 據(jù)說(shuō)高達(dá)60fps的刷新頻率(不卡)
1.Xcode新建My.html文件,自定義html內(nèi)容,主要代碼如下:
(1)標(biāo)簽為UI樣式(寫(xiě)了簡(jiǎn)單的JS代碼,目的用于講解交互)
(2)onClick為JS事件,當(dāng)JS想給OC傳遞參數(shù)時(shí),采用如下代碼:window.webkit.messageHandlers.<方法名>.postMessage(數(shù)據(jù))
<h1 style="text-align:center;background-color: #e6b500;wdith:100px;height:40px">歡迎來(lái)到JS世界</h1>
<p style="text-align:center"> <a href="github://callName_?https://github.com/wslcmk" rel="external nofollow" >Github主頁(yè)</a> :截獲URL調(diào)用OC</p>
<p style="text-align:center"> <a rel="external nofollow" >GitLab主頁(yè)</a> </p>
<p style="text-align:center"> <button id="btn1" type = "button" onclick = "jsToOcFunctionOne()" > JS調(diào)用OC->不帶參數(shù) </button> </p>
<p style="text-align:center"> <button id="btn2" type = "button" onclick = "jsToOcFunctionTwo()"> JS調(diào)用OC->帶參數(shù) </button> </p>
<p style="text-align:center"> <button id="btn3" type = "button" onclick = "showAlert()" > oc捕獲到html的彈出框 </button> </p>
<!-- JS語(yǔ)法-->
<script type = "text/javascript">
function jsToOcFunctionOne()
{
window.webkit.messageHandlers.jsToOcNoPrams.postMessage({});
}
function jsToOcFunctionTwo()
{
window.webkit.messageHandlers.jsToOcWithPrams.postMessage({"params":"我是JS參數(shù)"});
}
function showAlert()
{
alert("我來(lái)自JS世界,被你發(fā)現(xiàn)了");
}
//改變背景色
function changeBgColor()
{
document.body.style.backgroundColor = randomColor();
}
2.KVO實(shí)現(xiàn)加載進(jìn)度條以及標(biāo)題
// KVO:獲取進(jìn)度并顯示 獲取標(biāo)題并顯示
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"title"]&&object == _webView) {
self.title = _webView.title;
}else if ([keyPath isEqualToString:@"estimatedProgress"]
&& object == _webView)
{
self.progressView.progress = _webView.estimatedProgress;
if (_webView.estimatedProgress >= 1.0f) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
self.progressView.progress = 0;
});
}
}
}
3.通過(guò)攔截url方式,JS調(diào)用OC代碼,決定是否跳轉(zhuǎn)(WKNavigationDelegate)
#pragma mark -- WKNavigationDelegate WKNavigationDelegate主要處理一些跳轉(zhuǎn)、加載處理操作
// 根據(jù)WebView對(duì)于即將跳轉(zhuǎn)的HTTP請(qǐng)求頭信息和相關(guān)信息來(lái)決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSString * urlStr = navigationAction.request.URL.absoluteString;
NSLog(@"發(fā)送跳轉(zhuǎn)請(qǐng)求:%@",urlStr);
//自己定義的協(xié)議頭
NSString *htmlHeadString = @"github://";
if([urlStr hasPrefix:htmlHeadString]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"通過(guò)截取URL調(diào)用OC" message:@"前往Github?" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}])];
[alertController addAction:([UIAlertAction actionWithTitle:@"打開(kāi)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSURL * url = [NSURL URLWithString:[urlStr stringByReplacingOccurrencesOfString:@"github://callName_?" withString:@""]];
[[UIApplication sharedApplication]canOpenURL:url];
}])];
[self presentViewController:alertController animated:YES completion:nil];
decisionHandler(WKNavigationActionPolicyCancel);
}else{
decisionHandler(WKNavigationActionPolicyAllow);
}
}
4.OC獲取JS alert內(nèi)容(WKUIDelegate處理警告、輸入、以及確認(rèn),這里只列舉了alert。輸入和確認(rèn)就不一一列舉了,分別是JS端confirm和prompt函數(shù)觸發(fā))
當(dāng)調(diào)用JS端alert函數(shù)時(shí):通過(guò)如下獲取alert內(nèi)容
#pragma mark -- WKUIDelegate WKUIDelegate主要處理JS腳本,確認(rèn)框,警告框等
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"JS-alert-Action" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
5.OC調(diào)用JS代碼,實(shí)現(xiàn)改變JS頁(yè)面顏色(通過(guò)evaluateJavaScript函數(shù)、jsString為JS端方法名)
#pragma mark -navigationItem Action
- (void)ocToJs
{
// changeColor()是JS方法名
NSString *jsString = [NSString stringWithFormat:@"changeBgColor()"];
[_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
}];
}
6.通過(guò)接受JS方法名捕捉方法(帶參數(shù)和不帶參數(shù),JS端向IOS傳遞參數(shù),采用window.webkit.messageHandlers.<方法名>.postMessage(數(shù)據(jù)))
(1)需要引入WKUserContentController、主要代碼如下
//創(chuàng)建網(wǎng)頁(yè)配置對(duì)象
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKUserContentController * wkUController = [[WKUserContentController alloc] init];
//注冊(cè)一個(gè)name為jsToOcNoPrams的js方法 設(shè)置處理接收J(rèn)S方法的對(duì)象
[wkUController addScriptMessageHandler:self name:@"jsToOcNoPrams"];
[wkUController addScriptMessageHandler:self name:@"jsToOcWithPrams"];
config.userContentController = wkUController;
(2)核心代碼
#pragma mark - 通過(guò)接收J(rèn)S傳出消息的name進(jìn)行捕捉的回調(diào)方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
//用message.body獲得JS傳出的參數(shù)體
NSDictionary * parameter = message.body;
//JS調(diào)用OC
if([message.name isEqualToString:@"jsToOcNoPrams"]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js調(diào)用到了oc" message:@"不帶參數(shù)" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}])];
[self presentViewController:alertController animated:YES completion:nil];
}else if([message.name isEqualToString:@"jsToOcWithPrams"]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js調(diào)用到了oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Objective-C中編程中一些推薦的書(shū)寫(xiě)規(guī)范小結(jié)
這篇文章主要介紹了Objective-C的一些編程書(shū)寫(xiě)規(guī)范小結(jié),包括類(lèi)與方法等面向?qū)ο缶幊滔嚓P(guān)的代碼編寫(xiě)風(fēng)格,需要的朋友可以參考下2016-04-04
IOS使用NSUserDefault去實(shí)現(xiàn)界面?zhèn)髦岛蛿?shù)據(jù)存儲(chǔ)
這篇文章主要介紹了IOS使用NSUserDefault去實(shí)現(xiàn)界面?zhèn)髦岛蛿?shù)據(jù)存儲(chǔ)的相關(guān)資料,需要的朋友可以參考下2017-07-07
iOS中PNChart與UITableView的聯(lián)動(dòng)示例詳解
PNChart是個(gè)界面很漂亮的圖表第三方庫(kù),UITableView則不用過(guò)多介紹了,各位iOS開(kāi)發(fā)者們都知道,下面這篇文章主要給大家介紹了關(guān)于iOS中PNChart與UITableView的聯(lián)動(dòng)的相關(guān)資料,需要的朋友可以參考下2018-07-07
iOS NSURLSessionDownloadTask設(shè)置代理文件下載的示例
本篇文章主要介紹了iOS NSURLSessionDownloadTask設(shè)置代理文件下載的示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
iOS報(bào)Multiple?commands?produceMultiple錯(cuò)誤的解決方案
這篇文章主要為大家介紹了iOS報(bào)Multiple?commands?produceMultiple錯(cuò)誤的解決方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
IOS 中 new 和 alloc init 的對(duì)比
這篇文章主要介紹了IOS 中 new 和 alloc init 的區(qū)別的相關(guān)資料,需要的朋友可以參考下2017-02-02

