iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 18
0
自我挑戰組

IOS app開發介紹系列 第 18

IOS app開發介紹 - 內嵌WebView (2) 與App互傳資訊

前一篇介紹了利用WKWebView內嵌一個網頁和實現回到上一頁與到下一頁的功能,這一篇要做的是要讓網頁和我們的App溝通,以下將分為App傳訊息給網頁和網頁傳訊息給App(網頁端以Javascript為例)


App傳訊息給網頁

在Javascript中定義一個負責溝通的interface (i.e function),例如我們在javascript中定義一個sendMessage(message) function如下:

        <script type="text/javascript">
            function sendMessage(message) {
                document.getElementById("name").innerHTML = message
                return "Got it"
            }
        </script>

接受一個message參數,並回傳"Got it給App",App端則利用WKWebView提供的function evaluateJavaScript來傳遞message與接收回傳的結果與資料,詳細code如下:

        webView.evaluateJavaScript("sendMessage('swift message')") { (result, err) in
            print(result, err)
        }

網頁傳訊息給App

我們需要利用WKWebViewConfiguration來定義interface讓網頁傳訊息給App,

        let configuration = WKWebViewConfiguration()        
        configuration.userContentController = WKUserContentController()
        configuration.userContentController.add(self, name: "ToApp")
        var webView = WKWebView(frame: self.view.frame, configuration: configuration)

在上述的程式碼中我們定義了"ToApp"的interface,然後我們App端也需要接收的code,接收的方式是利用WKScriptMessageHandler ,它提供了一個接收訊息的system callback didReceive 來接收message,詳細如下:

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body)
    }

定義好了溝通的interface和接收的callback後,網頁的Javascript只需要在一個function中呼叫
window.webkit.messageHandlers.ToApp.postMessage("Send message to Swift")
這樣就可以發送訊息給App
Note: ToApp是我們定義的interface name, "Send message to Swift"是我們要傳送的訊息,剩下其他部分都是固定的


一樣提供範例,包含一個網頁範本,完整專案連結如下:
https://github.com/tgnivekucn/WKWebView2


上一篇
IOS app開發介紹 - 內嵌WebView(1) 載入網頁
下一篇
IOS app開發介紹 - ViewController容器之 UITabBarController
系列文
IOS app開發介紹22
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言