iOS开发SwiftUI

SwiftUI WKWebView使用JS与Swift交互

import UIKit
import SwiftUI
import WebKit


class SceneDelegate: UIResponder, UIWindowSceneDelegate, WKScriptMessageHandler {
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body)
    }
    

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        
        let preferences = WKPreferences()
            preferences.javaScriptEnabled = true
            configuration = WKWebViewConfiguration()
            configuration.preferences = preferences
            configuration.userContentController = WKUserContentController()
            // 给webview与swift交互起一个名字:AppModel,webview给swift发消息的时候会用到
            configuration.userContentController.add(self, name: "AppModel")

        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView()

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}
var configuration = WKWebViewConfiguration()
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>SVH Map Demo</title>
	
</head>

	
<body>
	
	<!--SVG Data Start-->
	<svg width="302px" height="302px" viewBox="0 0 302 302" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <title>Map</title>
    <g id="SVG-Map" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="画板" transform="translate(-29.000000, -29.000000)">
            <g id="Map" transform="translate(29.000000, 29.000000)">
                <rect id="Background" fill="#FFFFFF" x="0" y="0" width="302" height="302"></rect>
                <line x1="51" y1="150.5" x2="251" y2="150.5" id="Line01" stroke="#2A6EBB" stroke-width="9" stroke-linecap="round"></line>
                <line x1="151.849648" y1="51" x2="151.150352" y2="250.998777" id="Line02" stroke="#F09438" stroke-width="9" stroke-linecap="round"></line>
                <circle id="L1_Point1" stroke="#428BDD" stroke-width="5" fill="#FFFFFF" cx="51" cy="151" r="6.5"></circle>
                <circle id="L1_Point2" stroke="#428BDD" stroke-width="5" fill="#FFFFFF" cx="118" cy="151" r="6.5"></circle>
                <circle id="L1_Point3" stroke="#428BDD" stroke-width="5" fill="#FFFFFF" cx="184" cy="151" r="6.5"></circle>
                <circle id="L1_Point4" stroke="#428BDD" stroke-width="5" fill="#FFFFFF" cx="251" cy="151" r="6.5"></circle>
                <circle id="L2_Point1" stroke="#F4B373" stroke-width="5" fill="#FFFFFF" transform="translate(151.000000, 51.000000) rotate(-270.000000) translate(-151.000000, -51.000000) " cx="151" cy="51" r="6.5"></circle>
                <circle id="L2_Point2" stroke="#F4B373" stroke-width="5" fill="#FFFFFF" transform="translate(151.000000, 118.000000) rotate(-270.000000) translate(-151.000000, -118.000000) " cx="151" cy="118" r="6.5"></circle>
                <circle id="L2_Point3" stroke="#F4B373" stroke-width="5" fill="#FFFFFF" transform="translate(151.000000, 184.000000) rotate(-270.000000) translate(-151.000000, -184.000000) " cx="151" cy="184" r="6.5"></circle>
                <circle id="L2_Point4" stroke="#F4B373" stroke-width="5" fill="#FFFFFF" transform="translate(151.000000, 251.000000) rotate(-270.000000) translate(-151.000000, -251.000000) " cx="151" cy="251" r="6.5"></circle>
            </g>
        </g>
    </g>
</svg>
	<!--SVG Data End-->

	<!--JS Action-->
	<script>
		//Line1
		var L1_Point01 = document.getElementById('L1_Point1');
		var L1_Point02 = document.getElementById('L1_Point2');
		var L1_Point03 = document.getElementById('L1_Point3');
		var L1_Point04 = document.getElementById('L1_Point4');
		//Line2
		var L2_Point01 = document.getElementById('L2_Point1');
		var L2_Point02 = document.getElementById('L2_Point2');
		var L2_Point03 = document.getElementById('L2_Point3');
		var L2_Point04 = document.getElementById('L2_Point4');
		
		//Action
		
		function ClickPoint(pointname){
			window.webkit.messageHandlers.AppModel.postMessage("WebView点击,发送消息给Swift!" + pointname);
		}
		
		L1_Point01.onclick = function(){ClickPoint(1);} 
		L1_Point02.onclick = function(){ClickPoint(2);} 
		L1_Point03.onclick = function(){ClickPoint(3);} 
		L1_Point04.onclick = function(){ClickPoint(4);} 
		
		L2_Point01.onclick = function(){ClickPoint(5);} 
		L2_Point02.onclick = function(){ClickPoint(6);} 
		L2_Point03.onclick = function(){ClickPoint(7);} 
		L2_Point04.onclick = function(){ClickPoint(8);} 
		
		
	</script>
	
</body>
</html>