How to show an HTML string on a UILabel in iOS?

Ios

Ios Problem Overview


I am getting a title in HTML format as

<p><span style="color: #000000;"><strong>Example </strong></span></p>

I need to show this HTML string in a UILabel. The color code and the font size should be same as the coming in HTML. When I am converting the HTML string into a NSString, only the text "Example" is coming, and not the color.

Is there any solution?

Thnx in advance

Till now I am trying by using a NSAttributedString in following way but by this way the whole HTML is printing:

UIFont *font = [UIFont systemFontOfSize:14.0];
UIFont *secondFont = [UIFont systemFontOfSize:10.0];
        
NSMutableDictionary *firstAttributes;
NSMutableDictionary *secondAttributes;
        
NSDictionary *firstAttributeFont = @{NSFontAttributeName:font};
NSDictionary *secondAttributeFont = @{NSFontAttributeName:secondFont};
        
[firstAttributes addEntriesFromDictionary:firstAttributeFont];
[secondAttributes addEntriesFromDictionary:secondAttributeFont];
        
[firstAttributes addEntriesFromDictionary:@{NSForegroundColorAttributeName:[UIColor clearColor]}];
[secondAttributes addEntriesFromDictionary:@{NSForegroundColorAttributeName:[UIColor clearColor]}];
        
        
        
NSString* completeString = [NSString stringWithFormat:@"%@",strTitle];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]     initWithString:completeString];
[attributedString setAttributes:firstAttributes range:[completeString rangeOfString:strTitle]];
//   [attributedString setAttributes:secondAttributes range:[completeString rangeOfString:self.secondAttributeText]];
Cell.lbl_Title.attributedText = attributedString;

Ios Solutions


Solution 1 - Ios

For iOS7 or more you can use this:

NSString * htmlString = @"<html><body> Some html string </body></html>";
NSAttributedString * attrStr = 
  [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] 
                                   options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
                        documentAttributes:nil error:nil];

UILabel * myLabel = [[UILabel alloc] init];
myLabel.attributedText = attrStr;

Solution 2 - Ios

Swift 2

let htmlText = "<p>etc</p>"

if let htmlData = htmlText.dataUsingEncoding(NSUnicodeStringEncoding) {
    do {
        someLabel.attributedText = try NSAttributedString(data: htmlData,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)
    } catch let e as NSError {
        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
    }
}

Swift 3

let htmlText = "<p>etc</p>"

if let htmlData = htmlText.data(using: String.Encoding.unicode) {
    do {
        let attributedText = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    } catch let e as NSError {
        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
    }
}

Solution 3 - Ios

Swift 4+

For Swift 4 and above use:

guard let data = "foo".data(using: String.Encoding.unicode) else { return }

try? titleLabel.attributedText = 
   NSAttributedString(data: data,
                   options: [.documentType:NSAttributedString.DocumentType.html], 
        documentAttributes: nil)

Solution 4 - Ios

I did this on UITextView as follows:

[detailView loadHTMLString:[NSString stringWithFormat:@"<div style='text-align:justify; font-size:13px;font-family:HelveticaNeue;color:#362932;'>%@",[model.dict valueForKey:@"description"]] baseURL:nil];

Or you can use RTLabel library: <https://github.com/honcheng/RTLabel> to display html text along with its formatting on a label.

Solution 5 - Ios

Extension for Swift 4+

extension UILabel {
  func set(html: String) {
    if let htmlData = html.data(using: .unicode) {
      do {
        self.attributedText = try NSAttributedString(data: htmlData,
                                                     options: [.documentType: NSAttributedString.DocumentType.html],
                                                     documentAttributes: nil)
      } catch let e as NSError {
        print("Couldn't parse \(html): \(e.localizedDescription)")
      }
    }
  }
}

Solution 6 - Ios

-(NSString*)convertHtmlPlainText:(NSString*)HTMLString{
	NSData *HTMLData = [HTMLString dataUsingEncoding:NSUTF8StringEncoding];
	NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:HTMLData options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:NULL error:NULL];
	NSString *plainString = attrString.string;
	
	return plainString;
}

UILabel * htmlLabel = [UILabel alloc] init];
htmlLabel.text = [self convertHtmlPlainText:htmlResponse];

Solution 7 - Ios

If Html Text is like

var planeText = "Unseen and not Purchased!"
//setting color to the text
var htmlText = "<font color=\"#f20707\">" + planeText + "</font>"  

We can set the text to UILabel like this

if let htmlData = htmlText.data(using: String.Encoding.unicode) {
    do {
         let attributedText = try NSAttributedString(data: htmlData,
             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
             documentAttributes: nil)   
         //Setting htmltext to uilable 
         uilable.attributedText = attributedText

       } catch let e as NSError {
         //setting plane text to uilable cause of err
         uilable.text = planeText
         print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
       }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvasudevView Question on Stackoverflow
Solution 1 - IossanjanaView Answer on Stackoverflow
Solution 2 - IosBaseZenView Answer on Stackoverflow
Solution 3 - IosJakub TruhlářView Answer on Stackoverflow
Solution 4 - IosmakView Answer on Stackoverflow
Solution 5 - IosOrkhan AlikhanovView Answer on Stackoverflow
Solution 6 - IosAdarsh G JView Answer on Stackoverflow
Solution 7 - Iosuser4696837View Answer on Stackoverflow