APP開發使用Webview也是很常見的,有些功能常用但難度不高,有些功能則需要與網頁端配合(JavaScript互動),有些是政策上的更新(例如ATS政策),以下將會就一些常用功能做舉例
1.控制回上一頁(~應該不用說明惹
    if self.WebKit.canGoBack {
        self.WebKit.goBack()
    }
2.控制去下一頁(~應該不用說明
    if WebKit.canGoForward {
        WebKit.goForward()
    }
3. 重整畫面(~應該也不用說明    WebKit.reload()
4.下拉刷新,就是在WEBVIEW頁面中手勢往下滑會在頁面上方會出現類似activity indicator view的圖示,伴隨著提示並於幾秒後進行重整
    var refreshControl = UIRefreshControl()
    override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            //下拉刷新畫面
            refreshControl.addTarget(self, action: #selector(refreshview), for: .valueChanged)
            //下拉時顯示提示字
            refreshControl.attributedTitle = NSAttributedString(string:REFRESHING ,attributes:[NSAttributedString.Key.foregroundColor : UIColor.white])
            //刷新標示的顏色
            refreshControl.tintColor = .white
            WebKit.scrollView.addSubview(refreshControl)
    }
    @objc func refreshview() {
        //刷新畫面
        WebKit.reload()
        //3秒後載入畫面停止刷新
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.refreshControl.endRefreshing()
        }
    }
5.取得目前的url
在WKNavigationDelegate與WKUIDelegate的FUNC中可以抓取當前的URL let loadUrl = webView.url!.absoluteString
6.WKWebview與JavaScript互動
在HTML中,加上這段
<head>
     <style>
         .font {
             font-size: 36pt
         }
     </style>
     <script language="javascript">
         function bnClick() {
             // 取得使用者在文字框輸入的資料
             var text = document.getElementById("text1").value;
             // IamTester 即 WKWebKit 在初始化時註冊的名字
             window.webkit.messageHandlers.IamTester.postMessage(text)
         }
     
     // 這個函數在 ViewController.swift 中呼叫
     function showAlertInApp(title) {
         // alert 必須在 ViewController.swift 中攔截並轉成 UIAlertController
         alert(title);
         var label = document.getElementById("label1");
         label.innerHTML = title;
     }
     </script>
 </head>
 <body>
     <!-- 文字框 -->
     <div><input id="text1" type="text" class="font"/></div><p/>
     <!-- 按鈕 -->
     <div><input type="button" class="font" value="Button" onClick="bnClick()"/></div><p/>
     <!-- 標籤 -->
     <div id="label1" class="font"></div>
 </body>
在viewcontroller中,先在loadView()中將webview註冊好要透過JavaScript傳遞的名稱
override func loadView() {
        let configuration = WKWebViewConfiguration()
        configuration.userContentController = WKUserContentController()
        // 註冊名稱 IamTester,讓網頁上的 JavaScript 可以透過window.webkit.messageHandlers.IamTester 傳資料給 App
        configuration.userContentController.add(self, name: "IamTester")
        webView = WKWebView(frame: .zero, configuration: configuration)
        webView.uiDelegate = self
        // 將 webView 取代掉原本預設的 view 元件
        view = webView
    }
JavaScript呼叫WKWebview
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
     // 收到的資料放在 message.body 中
     let tmp = message.body as! String
     // showAlertInApp 為網頁中的 JavaScript 函數
     webView.evaluateJavaScript(
         "showAlertInApp('didReceive~\(tmp)')",
         completionHandler: nil
     )
 }
JavaScript的alert事件,在WKWebView中需要透過WKUIDelegate的三個代理runJavaScriptAlertPanelWithMessage、runJavaScriptConfirmPanelWithMessage和runJavaScriptTextInputPanelWithPrompt來完成。
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
    let alert = UIAlertController(
        title: nil,
        message: "我是要彈出的訊息\(message)",
        preferredStyle: .alert
    )
    let okAction = UIAlertAction(
        title: "確定",
        style: .default,
        handler: nil
    )
    alert.addAction(okAction)
    present(alert, animated: true, completion: nil)
    completionHandler()
}
7.ATS政策(AppTransportSecurity)
App中拒絕連線至沒有ssl保護的網站,除非在Info頁面新增App Transport Security Settings且有另外設定允許的網站,例如:Allow Arbitrary Loads、Allow Arbitrary Loads in Web Content、Exception Domains等,才可開啟http的網站
以上為我所整理的會常用的網頁功能,若有遺漏再請大神們指教~感激不盡~