This guide explains how to establish seamless bidirectional communication between your iOS app and the LiSA LiSA Player running within a WebView. By leveraging native-to-JavaScript bridges and WebView event listeners, you can enable your Android app and the LiSA Player to exchange data, trigger events, and synchronize state in real time.
Whether you need to send commands from you app to the LiSA Player (e.g., changing app behavior or updating content) or pass data from the WebView back to your app (e.g., user actions or analytics), this guide will walk you through the necessary setup and best practices for efficient, secure, and reliable communication.
Receiving Messages
To receive messages from the LiSA Player in your iOS application, use a message handler in WKWebView.
Configure WKWebView to add a message handler:
import SwiftUI
import WebKit
struct WebView: UIViewRepresentable {
let urlString: String
func makeUIView(context: Context) -> WKWebView {
let webViewConfiguration = WKWebViewConfiguration()
webViewConfiguration.allowsInlineMediaPlayback = true
webViewConfiguration.preferences.isElementFullscreenEnabled = true
webViewConfiguration.mediaTypesRequiringUserActionForPlayback = []
webViewConfiguration.userContentController.add(context.coordinator, name: "MessageFromLiSA")
let webView = WKWebView(frame: .zero, configuration: webViewConfiguration)
webView.navigationDelegate = context.coordinator
webView.uiDelegate = context.coordinator // For handling UI interactions like alerts
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
uiView.load(request)
}
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator: NSObject, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate {
// Handle messages from LiSA
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "MessageFromLiSA" {
print("Received message from LiSA: \(message.body)")
// Handle the JSON message
}
}
}
}
The message handler is registered under the name MessageFromLiSA.
When the LiSA Player sends a message using window.webkit.messageHandlers.MessageFromLiSA.postMessage, the didReceive method in the Coordinator processes it.
You can parse and handle the message (JSON) within the didReceive method.
Sending Messages
To send messages from iOS to the LiSA Player, use the evaluateJavaScript method in your Swift code: