Getting memory leak when converting HTML string to AttributedString

Getting memory leak when converting HTML string to AttributedString using below String extension

Usage:

self.lblHeader.attributedText = "<H1>Hello world</H1><h2><b>, abc</b><h2>".html2AttributedString

String extension for converting HTML to attributed string

extension String {
    var html2AttributedString: NSMutableAttributedString? {
    autoreleasepool {
        let htmlData = self.data(using: String.Encoding(rawValue: String.Encoding.utf16.rawValue))
        let options = [
            NSAttributedString.DocumentReadingOptionKey.documentType:
            NSAttributedString.DocumentType.html
        ] as [NSAttributedString.DocumentReadingOptionKey : Any]
        let attributedString = try? NSMutableAttributedString(
            data: htmlData ?? Data(),
            options: options,
            documentAttributes: nil)
    
       return attributedString
   }
  }
}

As I found a memory leak due to below the line:

let options = [
        NSAttributedString.DocumentReadingOptionKey.documentType:
        NSAttributedString.DocumentType.html
    ] as [NSAttributedString.DocumentReadingOptionKey : Any]

is there any alternative solution? let me know.

Replies

My general advice on this front is to not rely on Foundation’s HTML support. See this thread for my thoughts on this.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"