LoginSignup
49
38

More than 5 years have passed since last update.

WKWebViewにおけるSwiftとJavaScriptにおける双方向通信

Last updated at Posted at 2017-11-07

最近、業務でWKWebViewを用いてWebアプリの一部をiOSアプリにのせ、音声認識部分をnative側で実装するハイブリッドアプリを開発していたのでその時のメモ。

NativeからWebアプリを操作

let script = String(format: "document.getElementById('iPadVolumeData').value = \"%@\";", str)
webView.evaluateJavaScript(script, completionHandler: nil)

このようにSwift経由でDOM操作が可能。
ちなみにcompletionHandlerの中身はscript実行の結果が戻る。このハンドラーはmain threadで実行されるらしい。

Appleの公式ドキュメント

The method sends the result of the script evaluation (or an error) to the completion handler. The completion handler always runs on the main thread.

JS側からNativeを操作

1.WKWebViewConfigurationをインスタンス化

let webConfiguration = WKWebConfiguration()

2.WKUserContentControllerをインスタンス化

let userController = WKUserContentController()

3.userControllerJavaScript側から呼び出すhandlerを登録。そして、WKScriptMessageHandlerプロトコルを実装するdelegateを設定。

userController.add(self, name: "startRecording")
userController.add(self, name: "toggleMicInput")
userController.add(self, name: "youtubeStart")
userController.add(self, name: "youtubeEnd")

4.configurationにuserControllerを登録

webConfiguration.userContentController = userController

5.webViewにconfigurationを登録

let webView = WKWebView(frame: .zero, configuration: webConfiguration)

6.WKScriptMessageHandlerプロトコルの実装
JavaScript側でmessageをnative側に送信するとデリゲートメソッドのfunc userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)が呼び出される。JSONを送信することも可能。

handler.js
let data = JSON.stringify({
       usingMic: this.$store.state.chat.mic.using
})
window.webkit.messageHandlers.toggleMicInput.postMessage(data)
ChatbotViewController+WKScriptMessageHandler.swift
import Foundation
import WebKit

extension ChatbotViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        switch message.name {
        case "startRecording":
            print("startRecordingが呼ばれる")
        case "toggleMicInput":
            print("toggleMicInputが呼ばれる") //<--が呼ばれる
            guard let contentBody = message.body as? String,
                let data = contentBody.data(using: String.Encoding.utf8) else { return }
                if let json = try! JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as? Dictionary<String, Bool>, let isUsingMic = json["usingMic"] {
                if isUsingMic {
                    print("micを使っている")
                } else {
                    print("micを使っていない")
                }
            }
        case "youtubeStart":
            print("youtubeStartが呼ばれる")
        case "youtubeEnd":
            print("youtubeStoppedが呼ばれる")
        default:
            print("default")
        }
    }
49
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
38