Search code examples
iosswiftunicodeuilabelnsattributedstring

Swift: Empty space adding while converting html string to attribute string


Receiving HTML type String from API .

Converting HTML to NSAttributeString --> Facing empty Space issue by Unicode - \u200b

How to remove this white space from HTML to NSAttributeString ?

API Response:

{
    "message" : "[<b>1-</b> Fill\U200b t\U200bhe \U200b\U200b\U200bBreak Do\U200bwn Table]"
}

Struct - Decoder:

{
    "message" : "[<b>1-</b> Fill the Break Down Table]"
}

UILabel Text:

labet.text = Message.message // [<b>1-</b> Fill the Break Down Table] - SHOWING IN UI

UILabel Attribute text:

labet.attributedText = Message.message.htmlAttributedString() 

Attribute Output:

attribute_output - SHOWING IN UI

Extension Code:

func htmlAttributedString() -> NSMutableAttributedString {

    guard let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
        else { return NSMutableAttributedString() }

    guard let formattedString = try? NSMutableAttributedString(data: data,
                                                    options: [.documentType: NSAttributedString.DocumentType.html,
                                                              .characterEncoding: String.Encoding.utf8.rawValue],
                                                    documentAttributes: nil )

     else { return NSMutableAttributedString() }

    return formattedString
}

Can any one guide me on this ? How to avoid this space ?


Solution

  • Try this one:

    labet.attributedText = Message.message.replacingOccurrences(of: "\u{200B}", with: "").htmlAttributedString()