<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ed on Medium]]></title>
        <description><![CDATA[Stories by Ed on Medium]]></description>
        <link>https://medium.com/@yeeedward?source=rss-a5f4e82cc8a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Ed on Medium</title>
            <link>https://medium.com/@yeeedward?source=rss-a5f4e82cc8a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:50:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yeeedward/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Create Custom Checkbox and Radio Button List In SwiftUI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/create-custom-checkbox-and-radio-button-list-in-swiftui-e59cff1ec17d?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/2600/1*CmgOufJnSBxs5qpQ_8lDxw.png" width="2800"></a></p><p class="medium-feed-snippet">A questionnaire-type application, it involves a bunch of checkbox and radio button lists. How do we implement those lists in SwiftUI?</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/create-custom-checkbox-and-radio-button-list-in-swiftui-e59cff1ec17d?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/create-custom-checkbox-and-radio-button-list-in-swiftui-e59cff1ec17d?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e59cff1ec17d</guid>
            <category><![CDATA[radio-button-list]]></category>
            <category><![CDATA[checkbox-list]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 13:21:03 GMT</pubDate>
            <atom:updated>2025-09-20T13:21:03.001Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Multilevel Bullet List In SwiftUI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/multilevel-bullet-list-in-swiftui-a720d67bd486?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/2600/1*gc3xVkLwvehztElBQlAA7w.png" width="2800"></a></p><p class="medium-feed-snippet">Implement a multilevel bullet list in SwiftUI. The article starts from a boring bullet list to a fancy one. It may surprise you!</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/multilevel-bullet-list-in-swiftui-a720d67bd486?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/multilevel-bullet-list-in-swiftui-a720d67bd486?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a720d67bd486</guid>
            <category><![CDATA[groups]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[multilevel-bullet-list]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 09:19:27 GMT</pubDate>
            <atom:updated>2025-09-16T09:19:27.029Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Display Hierarchical Information In SwiftUI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/display-hierarchical-information-in-swiftui-0175a7bb9ebd?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/1400/1*0OQxKvZmZDCndYJegDNPow.png" width="1400"></a></p><p class="medium-feed-snippet">A simple article that shows how to display hierarchical information in SwiftUI.</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/display-hierarchical-information-in-swiftui-0175a7bb9ebd?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/display-hierarchical-information-in-swiftui-0175a7bb9ebd?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0175a7bb9ebd</guid>
            <category><![CDATA[hierarchical-data]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[box-group]]></category>
            <category><![CDATA[outlinegroup]]></category>
            <category><![CDATA[disclosuregroup]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 02:55:38 GMT</pubDate>
            <atom:updated>2025-09-13T02:55:38.271Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Re-introducing Substring in Swift5 (Part 2)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/re-introducing-substring-in-swift5-part-2-04946d083bb1?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/2400/1*WlI8b6-ABh-cXFizURAMZw.png" width="2400"></a></p><p class="medium-feed-snippet">Part 2 shows how to solve a substring-of-substring problem with generic method.</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/re-introducing-substring-in-swift5-part-2-04946d083bb1?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/re-introducing-substring-in-swift5-part-2-04946d083bb1?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/04946d083bb1</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[substring]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 03:20:11 GMT</pubDate>
            <atom:updated>2024-06-07T03:20:11.333Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Re-introducing Substring in Swift5 (Part 1)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/re-introducing-substring-in-swift5-7d57444e0e45?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/2400/1*k-Biv15ZjBvAvyqhAIygYw.png" width="2400"></a></p><p class="medium-feed-snippet">The String.substring method has been deprecated in Swift 5. This article shows how to re-introduce a String.substring method.</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/re-introducing-substring-in-swift5-7d57444e0e45?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/re-introducing-substring-in-swift5-7d57444e0e45?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d57444e0e45</guid>
            <category><![CDATA[substring]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[javascript-substring]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Fri, 31 May 2024 07:38:20 GMT</pubDate>
            <atom:updated>2024-06-07T03:24:44.023Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[XCode SwiftUI Playground]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/xcode-swiftui-playground-310f5fefa1d7?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/2160/1*eRkj5EZ5Q6sLhmvdS6x40A.png" width="2160"></a></p><p class="medium-feed-snippet">This article shows you how to transform an XCode Playground project from UIKit to SwiftUI.</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/xcode-swiftui-playground-310f5fefa1d7?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/xcode-swiftui-playground-310f5fefa1d7?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/310f5fefa1d7</guid>
            <category><![CDATA[project-playground]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 12:43:52 GMT</pubDate>
            <atom:updated>2024-03-18T12:43:52.931Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Simple Guide to Safari View Controller and More (SwiftUI)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/a-simple-guide-to-safari-view-controller-and-more-swiftui-b19c55c06de9?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/2400/1*P_cUPu6kZAYBNz6YE-iJjg.png" width="2400"></a></p><p class="medium-feed-snippet">This article shows how to use Safari View Controller in SwiftUI.</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/a-simple-guide-to-safari-view-controller-and-more-swiftui-b19c55c06de9?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/a-simple-guide-to-safari-view-controller-and-more-swiftui-b19c55c06de9?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b19c55c06de9</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[sfsafariviewcontroller]]></category>
            <category><![CDATA[safari]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 13:00:43 GMT</pubDate>
            <atom:updated>2023-07-19T13:00:43.638Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Messaging Between WKWebView and Native Application in SwiftUI]]></title>
            <link>https://medium.com/@yeeedward/messaging-between-wkwebview-and-native-application-in-swiftui-e985f0bfacf?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e985f0bfacf</guid>
            <category><![CDATA[wkwebview]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[messaging]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Wed, 31 May 2023 01:41:28 GMT</pubDate>
            <atom:updated>2023-05-31T01:41:28.926Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explores inter-process communication between the WKWebView and the native side. It is going to concentrate on local/embedded web pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Co3H1ZdmD8DhPmIJ0IVyHg.jpeg" /><figcaption>Photo by Alex Andrews: <a href="https://www.pexels.com/photo/three-black-handset-toys-821754/">https://www.pexels.com/photo/three-black-handset-toys-821754/</a></figcaption></figure><h3>The Birth of WKWebView</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_pF76pBk03YsK5kgd_lYw.png" /></figure><p>When Apple releases the first version of Safari web browser for macOS in 2003, they also create the first generation programmable interface, <a href="https://developer.apple.com/documentation/webkit/webview">WebView</a> class, to display web content in a native application.</p><p>In 2007, Steve Jobs announced the first iPhone. In the subsequent year, iPhone 3G was released along with the WebKit framework. The framework contains another programmable interface for iOS, <a href="https://developer.apple.com/documentation/uikit/uiwebview">UIWebView</a> class.</p><p>Apple started working on the second generation of WebKit in 2010. Four years later, WKWebView is released to replace both the WebView (macOS) and UIWebView (iOS) classes. Both classes are deprecated in 2018.</p><p>That’s a brief history of WKWebView.</p><h3>What is WKWebView?</h3><p>The answer is in Apple’s documentation.</p><blockquote>A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app’s UI.</blockquote><p>The key point is a native application can display HTML and SwiftUI/UIKit components in the same view.</p><p><strong><em>Why should I combine HTML and native components together?</em></strong></p><blockquote>Use it when web technologies satisfy your app’s layout and styling requirements more readily than native views.</blockquote><p>Formatting textual content or any fancy UI with SwiftUI/UIKit can be quite challenging. HTML and CSS are proven technologies. If web developers can produce mobile-friendly websites, they can easily produce UI for native applications!</p><p>That spares native application developers to handle other tasks…</p><blockquote>A web view offers control over the navigation and user experience through delegate objects. Use the navigation delegate to react when the user clicks links in your web content, or interacts with the content in a way that affects navigation… Use the UI delegate to present native UI elements, such as alerts or contextual menus, in response to interactions with your web content.</blockquote><p>This article will explore a bit more.</p><p><strong><em>Where is the web content coming from?</em></strong></p><blockquote>Before your web view appears onscreen, load content from a web server using a <a href="https://developer.apple.com/documentation/foundation/urlrequest">URLRequest</a> structure or load content directly from a local file or HTML string.</blockquote><p>Naturally, a web browser loads web pages from the web server. It is interesting to know WKWebView can load web content from local files or even HTML strings.</p><p>Local web content!</p><p>That means the native application can still be functional when the device is offline! Furthermore, the native application can avoid network latency.</p><p>Let’s dive into WKWebView.</p><h3>Create A Base Web View</h3><pre>struct SwiftUIWebView: UIViewRepresentable {<br>    typealias UIViewType = WKWebView<br>    <br>    var vm: BaseWebViewVM<br><br>    // Initialize with a view-model<br>    init(viewModel: BaseWebViewVM) {<br>        self.vm = viewModel<br>    }<br>    <br>    func makeUIView(context: Context) -&gt; WKWebView {<br>        return vm.webView<br>    }<br>    <br>    func updateUIView(_ uiView: WKWebView, context: Context) {<br>    }<br>    <br>    func makeCoordinator() -&gt; Coordinator {<br>        return Coordinator(viewModel: vm)<br>    }<br>}<br><br>extension SwiftUIWebView {<br>    class Coordinator: NSObject {<br>        var viewModel: BaseWebViewVM <br>        <br>        init(viewModel: BaseWebViewVM) {<br>            self.viewModel = viewModel<br>        }<br>    }<br>}<br><br>class BaseWebViewVM: ObservableObject {<br>    @Published var webResource: String?<br>    var webView: WKWebView<br><br>    init(webResource: String? = nil) {<br>        self.webResource = webResource<br>        <br>        self.webView = WKWebView(frame: .zero,<br>                                 configuration: WKWebViewConfiguration())<br>    }<br><br>    func loadWebPage() {<br>        if let webResource = webResource {<br>            guard let url = URL(string: webResource) else {<br>                print(&quot;Bad URL&quot;)<br>                return<br>            }<br><br>            let request = URLRequest(url: url)<br>            webView.load(request)<br>        }<br>    }<br>}</pre><p>That’s all the code that it needs to show a web page in WKWebView.</p><h4>SwiftUIWebView</h4><p>WKWebView is a UIView. It must be represented by a structure that implements UIViewRepresentable.</p><p>SwiftUIWebView must initialize with an instance of BaseWebViewVM.</p><p>The makeUIView method returns an instance of WKWebView from the view model.</p><p>The makeCoordinator method returns an instance of Coordinator. The Coordinator contains delegate functions for the WKWebView. For the time being, it doesn’t do anything special.</p><h4>BaseWebViewVM</h4><p>BaseWebViewVM has a published property webResource. This property can be initialized through the class constructor (init method). It can also be populated through a user interface.</p><p>The constructor creates an instance of WKWebView but without loading the target webResource.</p><p>For the time being, the loadWebPage method will load an internet web resource. Later on, we will see how to handle local web content.</p><p>If you want to try it out in the XCode Playground, add the following:</p><pre>import SwiftUI<br>import WebKit<br>import PlaygroundSupport<br><br>// Include the code above<br><br>struct ContentView: View {<br>    let vm = BaseWebViewVM(webResource: &quot;http://www.google.com&quot;)<br>    <br>    var body: some View {<br>        SwiftUIWebView(viewModel: vm)<br>            .onAppear(perform: vm.loadWebPage)<br>    }<br>}<br><br>PlaygroundPage.current.setLiveView(ContentView())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ojewz36E1mC4BJc0tORSoA.png" /><figcaption>Screenshot from XCode</figcaption></figure><blockquote>If XCode Live View is not showing anything and there is no error, try to toggle the Live View under Editor menu or Option-Cmd-Return (⌥⌘⏎) keys.</blockquote><p>This is good for displaying internet web pages. Let’s see how to display local web content.</p><h3>Display Embedded Web Pages</h3><p>First, we will create a Web folder at the root of the XCode project. It contains all the web pages and related artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*skY5zqD3PVJ5AOOYKCPytw.png" /><figcaption>Sample local HTML file</figcaption></figure><p>The web content folder may or may not physically be part of the native application project. If they are separate entities, it is necessary to pay extra attention to source code management!</p><p><strong><em>How does the application access a specific HTML file?</em></strong></p><p>Let’s say the application needs to access the following web page in the Web folder: (see the above screenshot)</p><pre>Web/userGuide/section1/login.html</pre><p>This is a relative path. The application can only open files with absolute pathname.</p><pre># From a simulator<br><br>/Users/&lt;your user ID&gt;/Library/Developer/CoreSimulator/Devices/.../Web/userGuide/section1/login.html<br><br># From XCode Playground project<br><br>/var/folders/.../Web/userGuide/section1/login.html</pre><p>Here is the code to convert relative pathname to absolute pathname:</p><pre>let nswr = NSString(string: relativePath)<br><br>let pathName = nswr.deletingLastPathComponent<br>let fileExtension = nswr.pathExtension<br>let fileName = nswr.lastPathComponent.replacing(&quot;.\(fileExtension)&quot;, with: &quot;&quot;)<br><br>// pathName: Web/userGuide/section1<br>// fileName: login<br>// fileExtension: html<br><br>let absolutePath = Bundle.main.path(forResource: fileName,<br>                                    ofType: fileExtension,<br>                                    inDirectory: inDirectory)</pre><p>In the application main bundle, the path method tries to resolve the given file information into an absolute path. The method returns nil if the given file information is incorrect.</p><p>Once the application obtains an absolute pathname of an HTML file, it can load it into the web view.</p><pre>let url = URL(filePath: absolutePath)<br>webView.loadFileURL(url, allowingReadAccessTo: url)</pre><p>Instead of using the load method, for a file path, we need to use the loadFileURL method.</p><p>To put it into the perspective the sample code, we are going to add a new class called LocalWebViewVM. It is a subclass of BaseWebViewVM.</p><pre>class LocalWebViewVM: BaseWebViewVM {<br>    private func processWebResource(webResource: String) -&gt; (inDirectory: String,<br>                                                             fileName: String,<br>                                                             fileExtension: String) {<br>        // Code to breakdown a relative pathname into components<br>    }<br><br>    override func loadWebPage() {<br>        if let webResource = webResource {<br>            let (inDirectory,<br>                 fileName,<br>                 fileExtension) = processWebResource(webResource: webResource)<br><br>            guard let filePath = Bundle.main.path(forResource: fileName,<br>                                                  ofType: fileExtension,<br>                                                  inDirectory: inDirectory) else {<br>                print(&quot;Bad path&quot;)<br>                return<br>            }<br><br>            print(filePath)<br>            let url = URL(filePath: filePath)<br><br>            webView.loadFileURL(url, allowingReadAccessTo: url)<br>        }<br>    }<br>}</pre><p>The subclass overrides the loadWebPage method.</p><p>Update the ContentView with a different view model.</p><pre>struct ContentView: View {<br>    let vm = LocalWebViewVM(webResource: &quot;Web/userGuide/section1/login.html&quot;)<br>    <br>    var body: some View {<br>        SwiftUIWebView(viewModel: vm)<br>            .onAppear(perform: vm.loadWebPage)<br>    }<br>}</pre><blockquote>At this point, XCode Playground doesn’t show anything in the Live View. I’m not sure if it is a bug in XCode 14.3 or something else. So I switch to an iOS project.</blockquote><p>This is what it looks like in the Canvas. (Live View in XCode Playground)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*zAfYsC3wBL8wkPGzSs5BwA.png" /></figure><h3>Some User Interaction</h3><h4>Javascript Alert</h4><p>A web page or application may show an alert message to the user through the following Javascript code:</p><pre>alert(&quot;This is an alert&quot;);</pre><p>WKWebView won’t present a dialog box when it happens. Instead, it delegates the responsibility to the hosting application.</p><pre>struct SwiftUIWebView: UIViewRepresentable {<br>    ...<br><br>    func makeUIView(context: Context) -&gt; WKWebView {<br>        // Handle alert<br>        vm.webView.uiDelegate = context.coordinator<br>        <br>        return vm.webView<br>    }<br><br>    ...<br>}<br><br>extension SwiftUIWebView {<br>    class Coordinator: NSObject, WKUIDelegate {<br>        ...<br><br>        // webView function handles Javascipt alert<br>        func webView(_ webView: WKWebView,<br>                     runJavaScriptAlertPanelWithMessage message: String,<br>                     initiatedByFrame frame: WKFrameInfo,<br>                     completionHandler: @escaping () -&gt; Void) {<br>            viewModel.webPanel(message: message,<br>                               alertCompletionHandler: completionHandler)<br>        }<br>    }<br>}<br><br>enum JSPanelType {<br>    case alert<br>    <br>    var description: String {<br>        switch self {<br>        case .alert:<br>            return &quot;Alert&quot;<br>        }<br>    }<br>}<br><br>class BaseWebViewVM: ObservableObject {<br>    ...<br><br>    // MARK: - Properties for Javascript alert, confirm, and prompt dialog boxes<br>    @Published var showPanel: Bool = false<br>    var panelTitle: String = &quot;&quot;<br>    var panelType: JSPanelType? = nil<br>    <br>    var panelMessage: String = &quot;&quot;<br>        <br>    // Alert properties<br>    var alertCompletionHandler: () -&gt; Void = {}<br><br>    // Set the properties for the corresponding alert UI<br>    func webPanel(message: String,<br>                  alertCompletionHandler completionHandler: @escaping () -&gt; Void) {<br>        self.panelTitle = JSPanelType.alert.description // &quot;Alert&quot;<br>        self.panelMessage = message<br>        self.alertCompletionHandler = completionHandler<br>        self.panelType = .alert<br>        self.showPanel = true<br>    }<br>}</pre><p>First, the application needs to assign context.coordinator to the web view uiDelegate property.</p><p>The Coordinator class needs to implement WKUIDelegate protocol and implement one of many webView functions. More specifically, the one for Javascript alert. The webView function does not initiate any UI presentation. Instead, it passes the alert message and a callback function to the view model.</p><p>Since the Javascript alert is a generic feature for any web page therefore it is best to implement the functionality in the BaseWebViewVM instead of its subclasses.</p><p>Here are some new properties:</p><p>showPanel — A published property that toggles the UI presentation in the ContentView.</p><p>panelTitle — A generic UI presentation title</p><p>panelMessage — A message comes from the web page</p><p>panelType — It indicates the type of UI presentation.</p><p>alertCompletionHandler — A specific Javascript alert callback function</p><p>The webPanel function sets panelType to JSPanelType.alert. It also set the showPanel to true that should trigger the corresponding UI presentation.</p><p>JSPanelType is an enumeration type. For the time being, it contains only an alert value. It also contains a computed property called description which returns a title description for a selected value.</p><p>Here is an updated ContentView:</p><pre>struct ContentView: View {<br>    @ObservedObject var vm = LocalWebViewVM(webResource: &quot;index.html&quot;)<br><br>    var body: some View {<br>        VStack {<br>            SwiftUIWebView(viewModel: vm)<br>                .onAppear(perform: vm.loadWebPage)<br>                .alert(vm.panelTitle,<br>                       isPresented: $vm.showPanel,<br>                       actions: {<br>                    switch vm.panelType {<br>                    case .alert:<br>                        Button(&quot;Close&quot;) {<br>                            vm.alertCompletionHandler()<br>                        }<br>                    default:<br>                        Button(&quot;Close&quot;) {}<br>                    }<br>                }, message: {<br>                    Text(vm.panelMessage)<br>                })<br>        }<br>        .padding()<br>    }<br>}</pre><p>The SwiftUIWebView includes an alert modifier. The alert has a Close button. It is going to invoke the alertCompletionHandler function.</p><p>Here is the web page:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>  ...<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;button onclick=&quot;alert(&#39;This is an alert!&#39;)&quot;&gt;Alert&lt;/button&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*crNpOlR8VlOFpZSVQXkF-Q.gif" /><figcaption>Handle Javascript alert()</figcaption></figure><p>This is a standard presentation. However, it can implement as sheet,popover, or whatever UI is suitable for your application.</p><h4>Javascript Confirm</h4><p>A Javascript confirm function is similar to a javascript alert. In a standard presentation, the modal contains a message, an OK button, and a Cancel button.</p><pre>confirm(&quot;Are you sure?&quot;)</pre><p>Javascript confirm function returns TRUE when clicking on the OK button. Otherwise, it returns FALSE.</p><p>To handle the Javascript confirm in Swift, the application needs to add another WKUIDelegate webView function.</p><pre>extension SwiftUIWebView {<br>    class Coordinator: NSObject, WKUIDelegate {<br>        ...<br><br>        // webView function handles Javascript confirm<br>        func webView(_ webView: WKWebView,<br>                     runJavaScriptConfirmPanelWithMessage message: String,<br>                     initiatedByFrame frame: WKFrameInfo,<br>                     completionHandler: @escaping (Bool) -&gt; Void) {<br>            viewModel.webPanel(message: message,<br>                               confirmCompletionHandler: completionHandler)<br>        }<br>    }<br>}<br><br>enum JSPanelType {<br>    case alert<br>    case confirm<br>    <br>    var description: String {<br>        switch self {<br>        case .alert:<br>            return &quot;Alert&quot;<br>        case .confirm:<br>            return &quot;Confirm&quot;<br>        }<br>    }<br>}<br><br>class BaseWebViewVM: ObservableObject {<br>    ...<br><br>    // Confirm properties<br>    var confirmCompletionHandler: (Bool) -&gt; Void = { _ in }<br><br>    // Set the properties for the corresponding confirm UI<br>    func webPanel(message: String,<br>                  confirmCompletionHandler completionHandler: @escaping (Bool) -&gt; Void) {<br>        self.panelTitle = JSPanelType.confirm.description<br>        self.panelMessage = message<br>        self.confirmCompletionHandler = completionHandler<br>        self.panelType = .confirm<br>        self.showPanel = true<br>    }<br>}</pre><p>The webView function for Javascript confirm has a slightly different callback function signature.</p><pre>completionHandler: @escaping (Bool) -&gt; Void</pre><p>It takes a boolean argument value.</p><p>Add confirm value to the JSPanelType.</p><p>Add a confirmCompletionHandler property to the BaseWebViewVM. Add another webPanel function for the Javascript confirm. The panelType property is set to JSPanelType.confirm. Again, the showPanel is set to true and that triggers the UI presentation.</p><p>Here is an updated ContentView:</p><pre>struct ContentView: View {<br>    @ObservedObject var vm = LocalWebViewVM(webResource: &quot;index.html&quot;)<br><br>    var body: some View {<br>        VStack {<br>            SwiftUIWebView(viewModel: vm)<br>                .onAppear(perform: vm.loadWebPage)<br>                .alert(vm.panelTitle,<br>                       isPresented: $vm.showPanel,<br>                       actions: {<br>                    switch vm.panelType {<br>                    case .alert:<br>                        Button(&quot;Close&quot;) {<br>                            vm.alertCompletionHandler()<br>                        }<br>                    case .confirm:<br>                        Button(&quot;Ok&quot;) {<br>                            vm.confirmCompletionHandler(true)<br>                        }<br>                        Button(&quot;Cancel&quot;) {<br>                            vm.confirmCompletionHandler(false)<br>                        }<br>                    default:<br>                        Button(&quot;Close&quot;) {}<br>                    }<br>                }, message: {<br>                    Text(vm.panelMessage)<br>                })<br>        }<br>        .padding()<br>    }<br>}</pre><p>Here is an updated web page:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>  ...<br>  &lt;script&gt;<br>    ...<br>    function callConfirm() {<br>      if (confirm(&quot;This is a confirm dialog&quot;)) {<br>        document.getElementById(&quot;confirmValue&quot;).innerText = &quot;You hit ok&quot;;<br>      } else {<br>        document.getElementById(&quot;confirmValue&quot;).innerText = &quot;You hit cancel&quot;;<br>      }<br>    }    <br>  &lt;/script&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  ...<br>  &lt;div&gt;<br>    &lt;button onclick=&quot;callConfirm()&quot;&gt;Confirm&lt;/button&gt;<br>    &lt;div&gt;Confirmed? &lt;span id=&quot;confirmValue&quot;&gt;&lt;/span&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*DJyWQIktvhBdSEaqEIYJlw.gif" /><figcaption>Handle Javascript confirm()</figcaption></figure><h4>Javascript Prompt</h4><p>The last standard Javascript modal is prompt. The modal contains a text field for user input.</p><pre>var response = prompt(&quot;This is a prompt! How are you?&quot;, &quot;Great&quot;);</pre><p>The second and optional argument of the prompt function is a default value. The default value is passed through the webView delegate method.</p><p>Once again, the application needs to add another WKUIDelegate webView function, update JSPanelType, and add new properties and webPanel function in BaseWebViewVM class.</p><pre>extension SwiftUIWebView {<br>    class Coordinator: NSObject, WKUIDelegate {<br>        ...<br><br>        // webView function handles Javascript prompt<br>        func webView(_ webView: WKWebView,<br>                     runJavaScriptTextInputPanelWithPrompt prompt: String,<br>                     defaultText: String?,<br>                     initiatedByFrame frame: WKFrameInfo,<br>                     completionHandler: @escaping (String?) -&gt; Void) {<br>            viewModel.webPanel(message: prompt,<br>                               promptCompletionHandler: completionHandler,<br>                               defaultText: defaultText)<br>        }<br>    }<br>}<br><br>enum JSPanelType {<br>    case alert<br>    case confirm<br>    case prompt<br>    <br>    var description: String {<br>        switch self {<br>        case .alert:<br>            return &quot;Alert&quot;<br>        case .confirm:<br>            return &quot;Confirm&quot;<br>        case .prompt:<br>            return &quot;Prompt&quot;<br>        }<br>    }<br>}<br><br>class BaseWebViewVM: ObservableObject {<br>    ...<br><br>    // Prompt properties<br>    var promptInput: String = &quot;&quot;<br>    var promptCompletionHandler: (String?) -&gt; Void = { _ in }<br><br>    // Set the properties for the corresponding prompt UI<br>    func webPanel(message: String,<br>                  promptCompletionHandler completionHandler: @escaping (String?) -&gt; Void,<br>                  defaultText: String? = nil) {<br>        self.panelTitle = JSPanelType.prompt.description<br>        self.panelMessage = message<br>        self.promptInput = defaultText ?? &quot;&quot;<br>        self.promptCompletionHandler = completionHandler<br>        self.panelType = .prompt<br>        self.showPanel = true<br>}</pre><p>Note that the promptInput is a one-way binding. The webPanel method sets the promptInput with the defaultText or an empty string.</p><p>Here is an updated ContentView:</p><pre>struct ContentView: View {<br>    @ObservedObject var vm = LocalWebViewVM(webResource: &quot;index.html&quot;)<br><br>    var body: some View {<br>        VStack {<br>            SwiftUIWebView(viewModel: vm)<br>                .onAppear(perform: vm.loadWebPage)<br>                .alert(vm.panelTitle,<br>                       isPresented: $vm.showPanel,<br>                       actions: {<br>                    switch vm.panelType {<br>                    ...<br>                    case .prompt:<br>                        TextField(text: $vm.promptInput) {}<br>                        Button(&quot;Ok&quot;) {<br>                            vm.promptCompletionHandler(vm.promptInput)<br>                        }<br>                        Button(&quot;Cancel&quot;) {<br>                            vm.promptCompletionHandler(nil)<br>                        }<br>                    default:<br>                        Button(&quot;Close&quot;) {}<br>                    }<br>                }, message: {<br>                    Text(vm.panelMessage)<br>                })<br>        }<br>        .padding()<br>    }<br>}</pre><p>The TextField component binds to the view-model promptInput property.</p><p>The callback function passes the promptInput property value. Note that promptInput is a non-nullable String property. As a result, the callback will either be an empty string or user input.</p><p>Here is an updated web page:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>  ...<br>  &lt;script&gt;<br>    ...<br>    function callPrompt() {<br>      var response = prompt(&quot;This is a prompt! How are you?&quot;, &quot;Great&quot;);<br>      if (response) {<br>        document.getElementById(&quot;promptResult&quot;).innerText =<br>          &quot;Your response is: &quot; + response;<br>      } else {<br>        document.getElementById(&quot;promptResult&quot;).innerText = &quot;Cancelled&quot;;<br>      }<br>    }  &lt;/script&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  ...<br>  &lt;div&gt;<br>    &lt;button onclick=&quot;callPrompt()&quot;&gt;Prompt&lt;/button&gt;<br>    &lt;div&gt;&lt;span id=&quot;promptResult&quot;&gt;&lt;/span&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*rlolSsaDf_BRguFOB8td5Q.gif" /><figcaption>Handle Javascript prompt()</figcaption></figure><p>In HTML5, there is a <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog">dialog</a> element. It is used to create modal and non-modal dialog boxes in HTML.</p><p>You can create a custom alert, confirm and prompt modal dialog boxes using the dialog element. This approach allows you to style the modals to match the rest of the web application.</p><p>By using the dialog element, instead of writing Swift code, you need to write Javascript code to handle all user interactions. However, that does not mean you won’t be able to tell the host (native) about spawning a dialog box. In the next section, we will see how to send messages or events between the web page and the host (native) application.</p><h3>Communication Between Web Page and Native Application</h3><p>The WebKit framework is designed for Objective-C and Swift. There is also a Javascript portion called <a href="https://developer.apple.com/documentation/webkitjs">WebKit JS</a>. It is a Safari DOM extension. (That might be the original name!) Basically, it adds touch gesture events, styling, and visual effects to the Safari environment. In fact, some of those features have already been adopted as part of the W3C standards.</p><p>To send messages/data from a web page to a native application, the receiving side needs to have a “listener”, or a message handler in WebKit terminology, and the sender needs to have a message-sending function.</p><p>This section demonstrates how to create send-receive and send-receive-reply messaging from the web view to the native application.</p><p>Let’s start with the web content.</p><pre>&lt;!-- index2.html --&gt;<br><br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>  ...<br>  &lt;title&gt;Index 2&lt;/title&gt;<br>  &lt;script&gt;<br>    async function sendWebKitMessage(handler, message) {<br>      if (<br>        message != &quot;&quot; &amp;&amp;<br>        handler != &quot;&quot; &amp;&amp;<br>        window.webkit &amp;&amp;<br>        window.webkit.messageHandlers &amp;&amp;<br>        window.webkit.messageHandlers.hasOwnProperty(handler)<br>      ) {<br>        console.log(&quot;Going to send a message to&quot;, handler)<br>        var reply = await window.webkit.messageHandlers[handler].postMessage(message);<br>        return reply<br>      } else {<br>        throw Error(&quot;Something is missing!&quot;);<br>    }<br><br>    async function sendReceiveReply(handler, message, elementId) {<br>      try {<br>        var reply = await sendWebKitMessage(handler, message);<br><br>        var sanitizedReply = reply.replace(/&lt;/g, &quot;&amp;lt;&quot;).replace(/&gt;/g, &quot;&amp;gt;&quot;);<br>        document.getElementById(elementId).innerHTML = sanitizedReply;<br>      } catch (error) {<br>        document.getElementById(elementId).innerHTML = &quot;ERROR: &quot; + error.message;<br>      }<br>    }<br>  &lt;/script&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;div&gt;<br>    &lt;button onclick=&quot;sendWebKitMessage(&#39;fromWebPage&#39;, &#39;A message from web view&#39;)&quot;&gt;Send Message&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div style=&quot;margin-top: 15px&quot;&gt;<br>    &lt;button onclick=&quot;sendReceiveReply(&#39;getData&#39;, &#39;Send me some data&#39;, &#39;reply&#39;)&quot;&gt;Get Data&lt;/button&gt;<br>    &lt;div id=&quot;reply&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>We have two async Javascript functions. The sendWebKitMessage function is responsible to send a message to the native application. The sendReceiveReply function is responsible for sending a message and displaying the response from the native application.</p><p>The sendReceiveReply function invokes the sendWebKitMessage function. Nothing fancy. If there is an exception, it will display the error message in the web view.</p><p>The sendWebKitMessage function first validates the name handler, the message, and the existence of the message handler. If any part is missing, it throws an exception.</p><p>Here is a screenshot of an uncaught exception from the “Send Message” button, and a handled exception from the “Get Data” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYv7oYkV0_MfJURagaUsrg.png" /></figure><p>The handler is an object residing in the window.webkit.messageHandlers namespace. All message handlers have a method called postMessage. It is used to send messages/data to the native application.</p><p>There is a console.log in the sendWebKitMessage function. It is going to show a message in the web inspector console area.</p><p>Let’s make some changes to the native application UI and the web view inspectable by the Safari web browser.</p><pre>class BaseWebViewVM: ObservableObject {<br>    ...<br><br>    // Message from web view<br>    @Published var messageFromWV: String = &quot;&quot;<br><br>    init(webResource: String? = nil) {<br>        ...<br>        <br>#if DEBUG<br>        // Inspectabl web view<br>        self.webView.isInspectable = true<br>#endif<br>    }<br><br>    ...<br>}<br><br>struct ContentView: View {<br>    // This VM shows a local web page with send message<br>    @ObservedObject var vm = LocalWebViewVM(webResource: &quot;index2.html&quot;)<br><br>    var body: some View {<br>        VStack {<br>            SwiftUIWebView(viewModel: vm)<br>                ...<br>            Text(&quot;From the web view:\n\(vm.messageFromWV)&quot;)<br>        }<br>    }<br>}</pre><p>In the BaseWebViewVM, it adds a published property called messageFromWV. It is going to store the incoming message from the web view. A Text element binds to this variable.</p><pre>@Published var messageFromWV: String = &quot;&quot;<br><br>Text(&quot;From the web view:\n\(vm.messageFromWV)&quot;)</pre><p>The BaseWebViewVM initializer includes the following lines of code.</p><pre>#if DEBUG<br>    self.webView.isInspectable = true<br>#endif</pre><p>This allows Safari to inspect the web page inside the web view. Note that the sample web page has the title “Index 2”. When you run the application in an iOS simulator, you should be able to see the web page title under Develop &gt; Simulator sub-menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydXVvx14YMr9qMeQJO-NLA.png" /><figcaption>Screenshot from Safari on macOS</figcaption></figure><p>Let’s make those HTML buttons interact with the native application.</p><p>First, we need to define message handlers for “fromWebPage” and “getData”.</p><pre>struct SwiftUIWebView: UIViewRepresentable {<br>    ...<br><br>    func makeUIView(context: Context) -&gt; WKWebView {<br>        let userContentController = vm.webView<br>            .configuration<br>            .userContentController<br>        <br>        // Clear all message handlers, if any<br>        userContentController.removeAllScriptMessageHandlers()<br><br>        // Message handler without reply<br>        userContentController.add(context.coordinator,<br>                                  name: &quot;fromWebPage&quot;)<br><br>        // Message handlers with reply<br>        userContentController.addScriptMessageHandler(context.coordinator,<br>                                                      contentWorld: WKContentWorld.page,<br>                                                      name: &quot;getData&quot;)<br>        ...<br>    }<br>}</pre><p>The user content controller (<a href="https://developer.apple.com/documentation/webkit/wkusercontentcontroller">WKUserContentController</a>) “coordinates interactions between your app’s native code and the webpage’s scripts and other content.” It is a web view configuration (<a href="https://developer.apple.com/documentation/webkit/wkwebviewconfiguration">WKWebViewConfiguration</a>) component.</p><p>For a send-receive message handler, the application needs to use the user content controller’s add method.</p><p>For a send-receive-reply message handler, the application needs to use the user content controller’s addScriptMessageHandler method.</p><p>Both methods need to pass an object that implements the userContentController method and the name of the message handler. For send-receive messaging, the object must implement WKScriptMessageHandler protocol. For send-receive-reply messaging, the object must implement WKScriptMessageHandlerWithReply.</p><p>The addScriptMessageHandler also needs to know where to install the message handler. In this sample code, the application passes WKContentWorld.page to the contentWorld argument.</p><p>Naturally, the Coordinator will be handling message communication. Here is the implementation.</p><pre>extension SwiftUIWebView {<br>    class Coordinator: ..., WKScriptMessageHandler, WKScriptMessageHandlerWithReply {<br>        ...<br><br>        // MARK: - WKScriptMessageHandler delegate function<br><br>        // For send-receive messaging<br>        func userContentController(_ userContentController: WKUserContentController, <br>                                   didReceive message: WKScriptMessage) {<br>            self.viewModel.messageFrom(fromHandler: message.name,<br>                                       message: message.body)<br>        }<br><br>        // MARK: - WKScriptMessageHandlerWithReply delegate function<br><br>        // For send-receive-reply messaging<br>        func userContentController(_ userContentController: WKUserContentController,<br>                                   didReceive message: WKScriptMessage,<br>                                   replyHandler: @escaping (Any?, String?) -&gt; Void) {<br>            do {<br>                let returnValue = try self.viewModel.messageFromWithReply(fromHandler: message.name,<br>                                                                          message: message.body)<br>                <br>                replyHandler(returnValue, nil)<br>            } catch WebViewErrors.GenericError {<br>                replyHandler(nil, &quot;A generic error&quot;)<br>            } catch WebViewErrors.ErrorWithValue(let value) {<br>                replyHandler(nil, &quot;Error with value: \(value)&quot;)<br>            } catch {<br>                replyHandler(nil, error.localizedDescription)<br>            }<br>        }<br>    }<br>}</pre><p>Both userContentController implementations receive a reference to the user content controller and the incoming message.</p><p>The message (WKScriptMessage) contains two important parameters — the name of the message handler (name) and the message content (body). In this sample code, both implementations invoke a view model method with the name and the body.</p><p>For the send-receive-reply version, there is an additional replyHandler closure argument. The closure has two arguments — a return value and an error message. When invoking the closure, the application passes “something” over to one of the arguments and the other one is nil.</p><p>Finally, the application needs to implement methods to execute the intent of the incoming message.</p><pre>class BaseWebViewVM: ObservableObject {<br>    ...<br><br>    // MARK: - Functions for messaging<br>    func messageFrom(fromHandler: String, message: Any) {<br>        self.panelTitle = JSPanelType.alert.description // &quot;Alert&quot;<br>        self.panelMessage = String(describing: message)<br>        self.alertCompletionHandler = {}<br>        self.panelType = .alert<br>        self.showPanel = true<br>        self.messageFromWV = String(describing: message)<br>    }<br><br>    func messageFromWithReply(fromHandler: String, message: Any) throws -&gt; String {<br>        self.messageFromWV = String(describing: message)<br><br>        var returnValue: String = &quot;Good&quot;<br><br>        /*<br>         * This function can throw the follow exceptions:<br>         *<br>         * - WebViewErrors.GenericError<br>         * - WebViewErrors.ErrorWithValue(value: 99)<br>         */<br>        <br>        if fromHandler == &quot;getData&quot; {<br>            returnValue = &quot;{ data: \&quot;It is good!\&quot; }&quot;<br>        }<br>        <br>        return returnValue<br>    }<br>}</pre><p>The messageFrom method is responsible for send-receive messaging. Note that it does not throw an exception. Even if it does, the userContentController method will not be able to pass the error back to the web view. If it is necessary to send the error back to the web view, the application should use the send-receive-reply messaging strategy — the messageFromWithReply method!</p><p>The messageFromWithReply method throws an exception and returns a string value. In the sample code, it returns a JSON string back to the web view. In the Javascript world, a JSON string can be easily parsed into Javascript objects.</p><p>The sample code doesn’t currently throw any exceptions. However, here are the errors defined in the sample project.</p><pre>enum WebViewErrors: Error {<br>    case ErrorWithValue(value: Int)<br>    case GenericError<br>}</pre><p>The first error accepts an integer value. It can be more than one argument.</p><p>Customize the enum per your application!</p><p>Finally, this is what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*-PYrd32kdzvXGs27tgr8yQ.gif" /></figure><p><strong><em>What about sending messages from the native application to the web view?</em></strong></p><p>In order to receive messages from the native application, the web page needs to “listen” to a message event.</p><p>Here is a sample web page:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>  ...<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;div&gt;<br>    &lt;label for=&quot;&quot;&gt;Message from the host:&lt;/label&gt;<br>    &lt;br&gt;<br>    &lt;div id=&quot;message&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;script&gt;<br>  window.addEventListener(&quot;message&quot;, (event) =&gt; {<br>    // Sanitize incoming message<br>    var content = event.data.replace(/&lt;/g, &quot;&amp;lt;&quot;).replace(/&gt;/g, &quot;&amp;gt;&quot;)<br>    document.getElementById(&quot;message&quot;).innerHTML = content<br>  })<br>&lt;/script&gt;<br><br>&lt;/html&gt;</pre><p>The web page adds a “message” event listener. The event.data contains the message content.</p><p>When the web page receives a “message”, it simply displays the content on this web page.</p><p>Let’s create a UI to send a message to the web view.</p><pre>struct MessageToWebView: View {<br>    @ObservedObject var vm = LocalWebViewVM(webResource: &quot;index3.html&quot;)<br>    @State var message: String = &quot;&quot;<br>    <br>    var body: some View {<br>        VStack(alignment: .leading) {<br>            Text(&quot;Message:&quot;)<br>                .font(.system(size: 26))<br>            HStack(alignment: .center, spacing: 10) {<br>                TextField(&quot;Enter a message&quot;, text: $message)<br>                    .textFieldStyle(.roundedBorder)<br>                    .border(.blue)<br>                    .font(.system(size: 26))<br>                Button(&quot;Send&quot;) {<br>                    vm.messageTo(message: message)<br>                }<br>                .buttonStyle(.borderedProminent)<br>            }<br>            WebView(vm: vm)<br>        }<br>        .padding()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*kUwG8ln8ta27iTZCl62g5Q.png" /></figure><p>The “Send” button invokes the messageTo method in the view model.</p><pre>func messageTo(message: String) {<br>    let escapedMessage = message.replacingOccurrences(of: &quot;\&quot;&quot;, with: &quot;\\\&quot;&quot;)<br>    <br>    let js = &quot;window.postMessage(\&quot;\(escapedMessage)\&quot;, \&quot;*\&quot;)&quot;<br>    self.webView.evaluateJavaScript(js) { (result, error) in<br>        if let error = error {<br>            print(&quot;Error: \(error.localizedDescription)&quot;)<br>        }<br>    }<br>}</pre><p>Unlike other scenarios above, there is no protocol method that needs to be implemented. There is no native method to send messages to the web view.</p><p>Instead, the native application needs to construct a Javascript postMessage call.</p><pre>window.postMessage(...)</pre><p>The postMessage method accepts a text argument. As a result, the content must escape and encode properly before executing by the web view evaluateJavaScript method.</p><pre>func evaluateJavaScript(<br>    _ javaScriptString: String,<br>    completionHandler: ((Any?, Error?) -&gt; Void)? = nil<br>)</pre><p>The evaluateJavaScript has a completionHandler. It is the way to pass the return value or error back to the native application.</p><p>Note that the evaluateJavaScript method can evaluate or execute any Javascript code. In our sample code, the window.postMessage call does not return any value or error. In other cases, the code being executed may return a value and throw an exception.</p><p>Finally, we can see it in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*AZXEKStS4IuR49Ho-HwihA.gif" /></figure><blockquote>NOTE: Web inspector does not automatically show the event contents. You need to add a console.log() in the Javascript code.</blockquote><p>In the above web page, it contains a script element that contains an event listener declaration.</p><p>If the application needs to inject the same Javascript code into all web pages. Instead of manually adding a script element to every web page, the application can utilize the user content controller addUserScript method.</p><p>Here is a simple implementation:</p><pre>struct SwiftUIWebView: UIViewRepresentable {<br>    ...<br><br>   func makeUIView(context: Context) -&gt; WKWebView {<br>      ...<br><br>      injectJS(userContentController)<br><br>      ...<br>    }<br><br>    func injectJS(_ userContentController: WKUserContentController) {<br>        // Define message event listener.<br>        //<br>        // Note that there is no need to include the &lt;script&gt; HTML element<br>        let msgEventListener = &quot;&quot;&quot;<br>window.addEventListener(&quot;message&quot;, (event) =&gt; {<br>    // Sanitize incoming message<br>    var content = event.data.replace(/&lt;/g, &quot;&amp;lt;&quot;).replace(/&gt;/g, &quot;&amp;gt;&quot;)<br>    document.getElementById(&quot;message&quot;).innerHTML = content<br>})<br>&quot;&quot;&quot;<br><br>        // Inject event listener<br>        userContentController.addUserScript(WKUserScript(source: msgEventListener,<br>                                                         injectionTime: .atDocumentEnd,<br>                                                         forMainFrameOnly: true))<br>    }<br>}</pre><p>The injectJS function contains a variable (msgEventListener) that has the same event listener code.</p><p>The addUserScript requires an instance of WKUserScript.</p><p>The injectionTime is set to .atDocumentEnd. This is identical to the original script element declaration. Another value is .atDocumentStart.</p><p>If the Javascript code depends on the content element, it might be best to inject the code at .atDocumentEnd.</p><p>If the Javascript code is a library, it might be best to inject the code at .atDocumentStart.</p><p>The forMainFrameOnly argument is a boolean value. Passing a true will inject the Javascript code only to the main web page. The application will not inject the same Javascript code into all iframe elements. Otherwise, the Javascript code will be injected into the main web page and its iframe elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*2j20w4gUhyJeloHrHLA3kA.png" /><figcaption>Web page without the script element</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*_jskan5L6NFxaFJJUCBzug.png" /><figcaption>Injected Javascript block</figcaption></figure><p>In the web inspector, the injected Javascript code is shown under “Extra Scripts &gt; user-script:1”</p><p>If the user navigates to another web page through a hyperlink, the application will inject the same Javascript block into the targetted web page.</p><p>Let’s add an iframe to this web page and set the forMainFrameOnly to false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*y1VGByqREwwcf4IIK4IsZw.png" /><figcaption>Web page with an iframe element</figcaption></figure><p>The web inspector shows two “user-script:1”. Each web page receives a block of Javascript code.</p><h3>Usage Scenarios</h3><h4>In-app User Guide</h4><p>If you need to provide a user guide or context-sensitive help information in an iOS or macOS application, how would you do that?</p><p>Both UIKit UILabel and SwiftUI Text elements support basic markdown format. Creating a useful help page with formatted text and images is quite cumbersome.</p><p>A help page can also compose as a web page using HTML and CSS. Help pages can be embedded inside an application and displayed using WKWebView.</p><h4>User Interface</h4><p>Instead of making the entire native application using either SwiftUI or UIKit, you can implement most of the user interface using HTML and CSS. Most of the business logic can be implemented using Javascript.</p><p>Javascript frameworks such as <a href="https://react.dev/">ReactJS</a>, <a href="https://angular.io/">Angular</a>, <a href="https://vuejs.org/">VueJS</a>, etc. can help to construct the front-end logic.</p><p>Javascript UI libraries, such as <a href="https://getbootstrap.com/">Bootstrap</a>, <a href="https://get.foundation/">Foundation</a>, <a href="https://semantic-ui.com/">Semantic UI</a>, <a href="https://tailwind-elements.com/">Tailwind Elements</a>, etc. provide a lot of attractive UI components. They are customizable to match the native application&#39;s look and feel.</p><p>Of course, using these libraries and frameworks may increase the size of the application. Use them wisely!</p><h3>Sample XCode Project</h3><p>You can access the corresponding XCode project at GitHub <a href="https://github.com/ed-yee/wkwebview_demo.git">here</a>.</p><h3>References</h3><ul><li><a href="https://developer.apple.com/documentation/webkit/wkwebview">WKWebView</a></li><li><a href="https://developer.apple.com/documentation/swiftui/uiviewrepresentable/">UIViewRepresentable</a></li><li><a href="https://developer.apple.com/documentation/swiftui/nsviewcontrollerrepresentable/coordinator">Coordinator</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkuidelegate">WKUIDelegate</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkusercontentcontroller">WKUserContentController</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkwebviewconfiguration">WKWebViewConfiguration</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkcontentworld">WKContentWorld</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkscriptmessagehandler">WKScriptMessageHandler</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkscriptmessagehandlerwithreply">WKScriptMessageHandlerWithReply</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkscriptmessage/">WKScriptMessage</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage">DOM message event and window.postMessage method</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkuserscript">WKUserScript</a></li></ul><p>This is the end of this article. Hopefully, it can give you some idea of how you might utilize the WKWebView in your project.</p><p>I hope you enjoy reading this article. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e985f0bfacf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Alignment In SwiftUI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/text-alignment-in-swiftui-36723b5179f2?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/2600/1*C2Q7KseClsiJwVMB2P4wXQ.png" width="2880"></a></p><p class="medium-feed-snippet">The are different ways to align contents within a SwiftUI Text element. This article will look at two different methods, and examine their&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/text-alignment-in-swiftui-36723b5179f2?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/text-alignment-in-swiftui-36723b5179f2?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/36723b5179f2</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[text-alignment]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 15:21:50 GMT</pubDate>
            <atom:updated>2023-01-30T16:35:09.592Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Syntax Highlighting in SwiftUI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@yeeedward/syntax-highlighting-in-swiftui-17486208ba8d?source=rss-a5f4e82cc8a2------2"><img src="https://cdn-images-1.medium.com/max/2600/1*okT1nEzMMeYs4oucYs-aRQ.png" width="2810"></a></p><p class="medium-feed-snippet">If you ever need to show source code in your Mac, iOS, or iPad OS application, this might be useful for you.</p><p class="medium-feed-link"><a href="https://medium.com/@yeeedward/syntax-highlighting-in-swiftui-17486208ba8d?source=rss-a5f4e82cc8a2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@yeeedward/syntax-highlighting-in-swiftui-17486208ba8d?source=rss-a5f4e82cc8a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/17486208ba8d</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[syntax-highlighting]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[nsregularexpression]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ed]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 07:14:21 GMT</pubDate>
            <atom:updated>2023-01-22T07:14:21.735Z</atom:updated>
        </item>
    </channel>
</rss>