溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

簡單說說iOS之WKWebView的用法小結

發布時間:2020-09-15 03:13:41 來源:腳本之家 閱讀:325 作者:小科科 欄目:移動開發

WKWebView的優勢

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

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

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

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

<h2 >歡迎來到JS世界</h2>

 <p > <a href="github://callName_?https://github.com/wslcmk" rel="external nofollow" >Github主頁</a> :截獲URL調用OC</p>

<p > <a  rel="external nofollow" >GitLab主頁</a> </p>
<p > <button id="btn1" type = "button" onclick = "jsToOcFunctionOne()" > JS調用OC->不帶參數 </button> </p>

<p > <button id="btn2" type = "button" onclick = "jsToOcFunctionTwo()"> JS調用OC->帶參數 </button> </p>


<p > <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參數"});
}

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

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

2.KVO實現加載進度條以及標題

//  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調用OC代碼,決定是否跳轉(WKNavigationDelegate代理)

#pragma mark -- WKNavigationDelegate  WKNavigationDelegate主要處理一些跳轉、加載處理操作
// 根據WebView對于即將跳轉的HTTP請求頭信息和相關信息來決定是否跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  
  NSString * urlStr = navigationAction.request.URL.absoluteString;
  NSLog(@"發送跳轉請求:%@",urlStr);
  //自己定義的協議頭
  NSString *htmlHeadString = @"github://";
  if([urlStr hasPrefix:htmlHeadString]){
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"通過截取URL調用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內容(WKUIDelegate處理警告、輸入、以及確認,這里只列舉了alert。輸入和確認就不一一列舉了,分別是JS端confirm和prompt函數觸發)

當調用JS端alert函數時:通過如下代理獲取alert內容

#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調用JS代碼,實現改變JS頁面顏色(通過evaluateJavaScript函數、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方法名捕捉方法(帶參數和不帶參數,JS端向IOS傳遞參數,采用window.webkit.messageHandlers.<方法名>.postMessage(數據))

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

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

(2)核心代碼

#pragma mark - 通過接收JS傳出消息的name進行捕捉的回調方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
  NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
  //用message.body獲得JS傳出的參數體
  NSDictionary * parameter = message.body;
  //JS調用OC
  if([message.name isEqualToString:@"jsToOcNoPrams"]){
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js調用到了oc" message:@"不帶參數" 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調用到了oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
  }  
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女