亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

簡單說說iOS之WKWebView的用法小結(jié)

 更新時間:2019年01月28日 14:39:42   作者:小科科  
iOS8.0之后我們使用 WebKit框架中的WKWebView來加載網(wǎng)頁。這篇文章主要介紹了簡單說說iOS之WKWebView的用法小結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

WKWebView的優(yōu)勢

  • 性能高,穩(wěn)定性好,占用的內(nèi)存比較小,
  • 支持JS交互
  • 支持HTML5 新特性
  • 可以添加進度條(不好用,還是習(xí)慣第三方的)。
  • 支持內(nèi)建手勢,
  • 據(jù)說高達60fps的刷新頻率(不卡)

1.Xcode新建My.html文件,自定義html內(nèi)容,主要代碼如下:

(1)標簽為UI樣式(寫了簡單的JS代碼,目的用于講解交互)

(2)onClick為JS事件,當(dāng)JS想給OC傳遞參數(shù)時,采用如下代碼:window.webkit.messageHandlers.<方法名>.postMessage(數(shù)據(jù))

<h1 style="text-align:center;background-color: #e6b500;wdith:100px;height:40px">歡迎來到JS世界</h1>

 <p style="text-align:center"> <a href="github://callName_?https://github.com/wslcmk" rel="external nofollow" >Github主頁</a> :截獲URL調(diào)用OC</p>

<p style="text-align:center"> <a  rel="external nofollow" >GitLab主頁</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語法-->
<script type = "text/javascript">
  
function jsToOcFunctionOne()
{
  window.webkit.messageHandlers.jsToOcNoPrams.postMessage({});
}

function jsToOcFunctionTwo()
{
  window.webkit.messageHandlers.jsToOcWithPrams.postMessage({"params":"我是JS參數(shù)"});
}

function showAlert()
{
  alert("我來自JS世界,被你發(fā)現(xiàn)了");
}

//改變背景色
function changeBgColor()
{
  document.body.style.backgroundColor = randomColor();
}

2.KVO實現(xiàn)加載進度條以及標題

//  KVO:獲取進度并顯示 獲取標題并顯示
  [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.通過攔截url方式,JS調(diào)用OC代碼,決定是否跳轉(zhuǎn)(WKNavigationDelegate)

#pragma mark -- WKNavigationDelegate  WKNavigationDelegate主要處理一些跳轉(zhuǎn)、加載處理操作
// 根據(jù)WebView對于即將跳轉(zhuǎn)的HTTP請求頭信息和相關(guān)信息來決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  
  NSString * urlStr = navigationAction.request.URL.absoluteString;
  NSLog(@"發(fā)送跳轉(zhuǎn)請求:%@",urlStr);
  //自己定義的協(xié)議頭
  NSString *htmlHeadString = @"github://";
  if([urlStr hasPrefix:htmlHeadString]){
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"通過截取URL調(diào)用OC" message:@"前往Github?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
      
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"打開" 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處理警告、輸入、以及確認,這里只列舉了alert。輸入和確認就不一一列舉了,分別是JS端confirm和prompt函數(shù)觸發(fā))

當(dāng)調(diào)用JS端alert函數(shù)時:通過如下獲取alert內(nèi)容

#pragma mark -- WKUIDelegate WKUIDelegate主要處理JS腳本,確認框,警告框等
- (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代碼,實現(xiàn)改變JS頁面顏色(通過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.通過接受JS方法名捕捉方法(帶參數(shù)和不帶參數(shù),JS端向IOS傳遞參數(shù),采用window.webkit.messageHandlers.<方法名>.postMessage(數(shù)據(jù)))

(1)需要引入WKUserContentController、主要代碼如下

//創(chuàng)建網(wǎng)頁配置對象
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKUserContentController * wkUController = [[WKUserContentController alloc] init];
    //注冊一個name為jsToOcNoPrams的js方法 設(shè)置處理接收JS方法的對象
    [wkUController addScriptMessageHandler:self name:@"jsToOcNoPrams"];
    [wkUController addScriptMessageHandler:self name:@"jsToOcWithPrams"];
    config.userContentController = wkUController;

(2)核心代碼

#pragma mark - 通過接收JS傳出消息的name進行捕捉的回調(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];
  }  
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論