Created
November 15, 2021 13:54
-
-
Save appfrosch/b2ea901ace83d5e2f4ae95c8cb0ef763 to your computer and use it in GitHub Desktop.
Display markdown string in a WebView in SiwftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import WebKit | |
import Ink | |
@main | |
struct poc_MarkdownToHtmlApp: App { | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
} | |
} | |
struct ContentView: View { | |
@State private var markdownInput = "# It works…" | |
var body: some View { | |
VStack { | |
TextEditor(text: $markdownInput) | |
.border(Color.blue, width: 2.0) | |
WebViewWrapper(markdownString: markdownInput) | |
.border(Color.red, width: 2.0) | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
#if os(macOS) | |
/// Bridges the AppKits WKWebView to SwiftUI, loading a markdown string. | |
/// | |
/// For the UIKit world, exchange all occurrences of `ns`/`NS` with `ui`/`UI` respectively. | |
/// > Do not forget to allow inbound network connections in the sandbox settings of the target! | |
struct WebViewWrapper: NSViewRepresentable { | |
let markdownString: String | |
init(markdownString: String) { | |
self.markdownString = markdownString | |
} | |
func makeNSView(context: Context) -> WKWebView { | |
return WKWebView() | |
} | |
func updateNSView(_ nsView: WKWebView, context: Context) { | |
let html = renderHtml(from: markdownString) | |
nsView.loadHTMLString(html, baseURL: nil) | |
} | |
func renderHtml(from markdownString: String) -> String { | |
// Make sure to import https://github.com/JohnSundell/Ink for markdown to html parsing | |
let parser = MarkdownParser() | |
let html = parser.html(from: markdownString) | |
return html | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment