1

I want to convert HTML Tag to String, I used enum to find the content length of the String, according to the length i need to do some operations.

My modal class,

class PostViewModel {
    var content: TextContent
    enum TextContent {
            case expanded(String)
            case collapsed(String)

            static func == (lhs: TextContent, rhs: TextContent) -> Bool {
                switch lhs {
                case .collapsed(let content):
                    if case collapsed(content) = rhs {
                        return true
                    }
                    return false
                case .expanded(let content):
                    if case expanded(content) = rhs {
                        return true
                    }
                    return false
                }
            }
        }
    }

And i am calling this function in cellForItem(at index: Int),

func applyVerticalSizeConcernedRendering(fromViewModel viewModel: PostViewModel) {
    switch viewModel.content {
        case .collapsed(let content):
            let str = content.html2String
            print(str)
        case .expanded(let content):
            break
    }
}

html2String is extension class of String

extension String {
      var html2AttributedString: NSMutableAttributedString? {
      guard let data = data(using: String.Encoding.utf8) else { return nil }
            let attrs: [String: Any] = [
                NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
            ]
            do {
                let attrStr = try NSMutableAttributedString(data: data, options: attrs, documentAttributes: nil)
                return attrStr
            } catch let error as NSError {
                print(error.localizedDescription)
                return  nil
            }
        }
        var html2String: String {
            return html2AttributedString?.string ?? ""
        }
    }

The problem is it's crashing while converting HTML tag to String

It's crashing here,

let attrStr = try NSMutableAttributedString(data: data, options: attrs, documentAttributes: nil)

And the String is not empty

Below is the example HTML String,

<strong>I want to test HTML Tags<br><\/strong>dsfhjdjf sjdfdj  djfjdfj djkf dfjdhf <strong>adjf<br>asks <\/strong>djfdkf<br><strong>dfdjk dkfjdk <\/strong>dfjik iai <strong>adsfhj<\/strong>

This is working fine when i tried with hardcode value, but it's crashing only when i get the String from the enum

And i don't know why the <code>String</code> is placed inside brackets. I hope, that's causing the crash

The crash log is,

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

Can anyone please help in this?

Austin Michael
  • 460
  • 4
  • 18

1 Answers1

1

Try out this instead, no need to do the whole process that you have done:

extension String {
    var htmlAttributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            print("error:", error)
            return nil
        }
    }
    var htmlString: String {
        return htmlAttributedString?.string ?? ""

}

Usage:

let html = "<strong>I want to test HTML Tags<br></strong>dsfhjdjf sjdfdj  djfjdfj djkf dfjdhf <strong>adjf<br>asks</strong>djfdkf<br><strong>dfdjk dkfjdk </strong>dfjik iai <strong>adsfhj</strong>"
let str = html.htmlString

So you basically just use the String extension on your Strings. This is what I use in my projects

Update:
The above prints the following:

enter image description here

Here is a example project that you can try.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • Still crashes but with different crash log, `-[_SwiftValue unsignedIntegerValue]: unrecognized selector sent to instance 0x60000025be70` `*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue unsignedIntegerValue]: unrecognized selector sent to instance 0x60000025be70'` – Austin Michael Sep 11 '17 at 13:31
  • That´s weird. Checkout my update of what my code prints out and I have also added a sample project that you can try. – Rashwan L Sep 11 '17 at 13:40
  • Please see the updated question, it's working fine with hard coded values – Austin Michael Sep 11 '17 at 13:48
  • Even I had crashes : Exception NSException * "*** -[__NSArrayM objectAtIndexedSubscript:]: index 9 beyond bounds [0 .. 8]" 0x0000600002ae8240 But when I put the code in main thread DispatchQueue.main.async { it worked for me . I had though the issue was due to conversion. – Rajath Kornaya Jun 30 '22 at 13:59