0

I have a string that contains HTML code. What is the best way to display that (it contains images), also I want to make links in that tappable (open in Safari)

I have tried String extension that gives me NSAttributedString from HTML, but the image is only partially shown and links are not tappable.

let text = htmlString.attributedString(withRegularFont: UIFont.systemFont(ofSize: 14), andBoldFont: UIFont.systemFont(ofSize: 16))

extension String {

    func attributedString(withRegularFont regularFont: UIFont, andBoldFont boldFont: UIFont, textColor: UIColor = UIColor.gray) -> NSMutableAttributedString {
        var attributedString = NSMutableAttributedString()
        guard let data = self.data(using: .utf8) else { return NSMutableAttributedString() }
        do {
            attributedString = try NSMutableAttributedString(data: data,
            options: [.documentType: NSAttributedString.DocumentType.html,
            .characterEncoding:String.Encoding.utf8.rawValue],
            documentAttributes: nil)
            let range = NSRange(location: 0, length: attributedString.length)
            attributedString.enumerateAttribute(NSAttributedString.Key.font, in: range, options: .longestEffectiveRangeNotRequired) { value, range, _ in
            let currentFont: UIFont = value as! UIFont
            var replacementFont: UIFont? = nil

            if currentFont.fontName.contains("bold") || currentFont.fontName.contains("Semibold") {
                replacementFont = boldFont
            } else {
                replacementFont = regularFont
            }

            let replacementAttribute = [NSAttributedString.Key.font:replacementFont!, NSAttributedString.Key.foregroundColor: textColor]
            attributedString.addAttributes(replacementAttribute, range: range)
        } catch let e {
            print(e.localizedDescription)
        }
        return attributedString
    }
}

It shows me the HTML inside the UILabel but I am not able to tap on links and images are cropped respective to device width.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

2

I think that the best option is to save this html string as a file and then load this file using web view. check this question

kstefanou
  • 608
  • 10
  • 14
  • the html content is dynamic, its coming from api and i need to show that inside a collectionview that contains a tableview inside its cell – Nooralam Shaikh Jul 05 '19 at 09:24