Skip to content
This repository has been archived by the owner on Apr 18, 2023. It is now read-only.

Commit

Permalink
Parse HTML on main thread (#84)
Browse files Browse the repository at this point in the history
* Parse HTML on main thread

* PR Comment
  • Loading branch information
aelkady authored Jan 9, 2019
1 parent 888dae1 commit 5624cd7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
21 changes: 18 additions & 3 deletions Source/Text Parsing/RichTextParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,28 @@ class RichTextParser {
}
return (latex, nil)
}
if Thread.isMainThread {
return self.getAttributedTextFromDown(with: input)
}

var output = NSAttributedString(string: "")
var parsingError: ParsingError?

DispatchQueue.main.sync {
(output, parsingError) = self.getAttributedTextFromDown(with: input)
}

return (output, parsingError)
}

private func getAttributedTextFromDown(with input: String) -> (output: NSAttributedString, error: ParsingError?) {
guard let attributedInput = try? Down(markdownString: self.stripCodeTagsIfNecessary(from: input)).toAttributedString() else {
return (NSAttributedString(string: input), ParsingError.attributedTextGeneration(text: input))
}
var mutableAttributedInput = NSMutableAttributedString(attributedString: attributedInput)

let mutableAttributedInput = NSMutableAttributedString(attributedString: attributedInput)
mutableAttributedInput.replaceFont(with: self.font)
mutableAttributedInput = mutableAttributedInput.trimmingTrailingNewlinesAndWhitespaces()
return (mutableAttributedInput, nil)
return (mutableAttributedInput.trimmingTrailingNewlinesAndWhitespaces(), nil)
}

func seperateComponents(from input: String) -> [String] {
Expand Down
14 changes: 14 additions & 0 deletions UnitTests/Text Parsing/RichTextParserSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,20 @@ class RichTextParserSpec: QuickSpec {
expect(attributedStrings.count).to(equal(1))
expect(attributedStrings[0].string).to(equal("\nMessage"))
}
it("generates an attributed string array with the correct components for html on a non-main thread") {
waitUntil { done in
DispatchQueue.global().async {
let components = self.richTextParser.seperateComponents(from: MarkDownText.complexHTML)
let results = self.richTextParser.generateAttributedStringArray(from: components)
let attributedStrings = results.output

expect(attributedStrings.count).to(equal(1))
expect(attributedStrings[0].string).to(equal("\nMessage"))
done()
}
}

}
}
context("Rich text to attributed string") {
it("generates a single attributed string with multiple rich text types") {
Expand Down

0 comments on commit 5624cd7

Please sign in to comment.