How to use SwiftyMarkdown in SwiftUI?

SwiftyMarkdown is a great package, I try to process text in SwiftUI:

import SwiftUI
import SwiftyMarkdown

struct SwiftyMD: View {
    var body: some View {
        Text("Hello, Markdown!")
        SwiftUICallSwift()
    }
}

#Preview {
    SwiftyMD()
}

struct SwiftUICallSwift: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> some UIViewController {
        let vc = SwiftyMDViewController()
        // vc.color = color
        return vc
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
}

class SwiftyMDViewController: UIViewController {
    var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // self.textView.dataDetectorTypes = UIDataDetectorTypes.all

        if let url = Bundle.main.url(forResource: "README", withExtension: "md"), let md = SwiftyMarkdown(url: url) {
            md.h2.fontName = "Heiti"
            md.h2.color = UIColor.red
            md.h2.alignment = .left
            md.h6.fontName = "Heiti"
            md.h6.color = UIColor.brown
            md.h6.alignment = .left
            md.h6.fontSize = 20
            // md.code.fontName = "CourierNewPSMT"
            /*
             // 2023/10/27 by jumpfox
                        if #available(iOS 13.0, *) {
                            md.strikethrough.color = .tertiaryLabel
                        } else {
                            md.strikethrough.color = .lightGray
                        }

             */
            md.blockquotes.fontStyle = .italic
            md.underlineLinks = true
            self.textView.attributedText = md.attributedString()
        }
        // print(#error)
        fatalError("Error loading file")
    }
}

But I got error:

SwiftyMD.swift:67: Fatal error: Error loading file

How to resolve it ? Thanks!

  • 2

    Markdown is supported natively with LocalizedStringKey just do something like Text(LocalizedStringKey(/*your markdown string here*/))

    – 

  • leave out let md = SwiftyMarkdown(url: url) to see if the resource is loading.

    – 

Leave a Comment