Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Markdown-formatted string to NSAttributedString in Swift

Is there a way to convert a plain text string containing Markdown text (i.e., # heading, * list item, [a link](http://example.com), etc.) to an NSAttributedString in Swift? I suppose I could perform some kind of regex search for the indices of certain MD patterns and create the attributed string from that, but that seems clunky and feels wrong to me.

Is there an easier method?

like image 535
Matt Avatar asked Jun 15 '18 00:06

Matt


People also ask

What is NSAttributedString in Swift?

An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string.


2 Answers

You can try using a third party library like Down. It's a lot simpler than creating your own parsing engine.

After installing this library, you can use the following code to parse markdown strings to NSAttributedStrings:

let downMdStr = Down(markdownString: yourMarkdownString)
let attributedStr = try? down.toAttributedString()

attributedStr is an NSAttributedString. However, it may be nil if any error occurs, so remember to perform checking.

like image 192
Papershine Avatar answered Oct 17 '22 21:10

Papershine


iOS 15 now supports Markdown parsing directly by NSAttributedString/AttributedString class.

let markdownString = "..."
let attrString = try AttributedString(markdown: markdownString)

See details here: https://developer.apple.com/documentation/foundation/attributedstring

like image 13
Skie Avatar answered Oct 17 '22 22:10

Skie