Created
February 20, 2023 21:27
-
-
Save eliakorkmaz/db3e743dbd5f704326094599c06ac8c5 to your computer and use it in GitHub Desktop.
This file contains 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 UIKit | |
class MarkdownPreviewViewController: UIViewController { | |
@IBOutlet weak var markdownTextView: UITextView! | |
private var markdownPreviewer = MarkdownPreviewer() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
Task { | |
await prepareMarkdown(from: "https://www.awesomemarkdownresourcetouse.com") | |
} | |
} | |
} | |
extension MarkdownPreviewViewController { | |
func prepareMarkdown(from url: String) async { | |
do { | |
try await markdownPreviewer.showMarkdown(in: markdownTextView, url: url) | |
} catch { | |
print(error.localizedDescription) | |
} | |
} | |
} | |
@MainActor class MarkdownPreviewer { | |
private struct MarkdownWorker { | |
static func parse(markdown: String) -> String { markdown } | |
@discardableResult static func cache(markdown: String) -> String { markdown } | |
} | |
private func prepareMarkdown(contentsOf url: String) async throws -> String { | |
let url = URL(string: url)! | |
let (data, _) = try await URLSession.shared.data(from: url) | |
let downloadedMarkdownData = String(data: data, encoding: .utf8) ?? "" | |
let parsedMarkdown = MarkdownWorker.parse(markdown: downloadedMarkdownData) | |
let cachedMarkdown = MarkdownWorker.cache(markdown: parsedMarkdown) | |
return cachedMarkdown | |
} | |
func showMarkdown(in textview: UITextView, url: String) async throws { | |
do { | |
let markdownData = try await prepareMarkdown(contentsOf: url) | |
textview.text = markdownData | |
} catch { | |
print(error.localizedDescription) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment