비전공자 개발일기

Webview (Local html) 본문

SWIFT

Webview (Local html)

HiroDaegu 2023. 2. 21. 23:14
728x90
SMALL
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
        
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(webView)
        NSLayoutConstraint.activate([
            webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            webView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor),
            webView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor)
        ])
        
        if let url = Bundle.main.url(forResource: "index", withExtension: "html") {
            webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
        }

        let contentController = self.webView.configuration.userContentController
        contentController.add(self, name: "toggleMessageHandler")
        let js = """
            var _selector = document.querySelector('input[name=myCheckbox]');
            _selector.addEventListener('change', function(event) {
                var message = (_selector.checked) ? "Toggle Switch is on" : "Toggle Switch is off";
                if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.toggleMessageHandler) {
                    window.webkit.messageHandlers.toggleMessageHandler.postMessage({
                        "message": message
                    });
                }
            });
        """
        let script = WKUserScript(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
        contentController.addUserScript(script)
    }
    
    private lazy var webView: WKWebView = {
        let webView = WKWebView()
        webView.translatesAutoresizingMaskIntoConstraints = false
        return webView
    }()
}

extension ViewController:WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        guard let dict = message.body as? [String: AnyObject] else { return }
        print(dict)
        guard let message = dict["message"] else { return }
        let script = "document.getElementById('value').innerText = \"\(message)\""
        webView.evaluateJavaScript(script) { (result, error) in
            if let result = result {
                print("Label is updated with message: \(result)")
            } else if let error = error {
                print("An error occurred \(error)")
            }
        }
    }
}
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: #2598EB;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 30px;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        label.switch {
            outline: none;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #CCC;
            -webkit-transition: .4s;
            transition: .4s;
            outline: none;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: #FFF;
            -webkit-transition: .4s;
            transition: .4s;
        }

        input:checked+.slider {
            background-color: #BB2649;
        }

        input:focus+.slider {
            box-shadow: 0 0 1px #BB2649;
        }

        input:checked+.slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        .slider.round {
            border-radius: 34px;
        }

        .slider.round:before {
            border-radius: 50%;
        }
    </style>
</head>

<body>
    <h2 id="value">Toggle Switch is off</h2>
    <label class="switch">
        <input type="checkbox" name="myCheckbox">
        <span class="slider round"></span>
    </label>
    <script>
        var _selector = document.querySelector('input[name=myCheckbox]');
        _selector.addEventListener('change', function (event) {
            var message = (_selector.checked) ? "Toggle Switch is on" : "Toggle Switch is off";
            if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers
                .toggleMessageHandler) {
                window.webkit.messageHandlers.toggleMessageHandler.postMessage({
                    "message": message
                });
            }
        });
    </script>
</body>

</html>
728x90
LIST

'SWIFT' 카테고리의 다른 글

Location Information in Background Mode(iOS - Swift)  (0) 2023.02.24
Dark Mode(Light Mode) 고정하기(무시하기)  (0) 2023.02.22
QR Code Scanner Example  (0) 2023.02.20
Random Chinese character Generator  (0) 2023.01.29
Memo App made by SwiftUI  (0) 2023.01.17