0

A web service is giving me some strings with HTML tags like <b></b>, <i></i> and so on.

I need to convert those strings to attributed text to be able to show them in labels.

This is what I'm using so far:

NSError *err;
NSAttributedString *obj = [[[NSAttributedString alloc] initWithData: [str dataUsingEncoding:NSUTF8StringEncoding]
                                                            options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
                                                 documentAttributes: nil
                                                              error: &err] defaultFontSized:KDefaultFontSize];

Then I try to use the resulting string in my label:

label.attributedText = obj;

Well, this doesn't work, for some reason beyond my knowledge.

Any help would be greatly appreciated.

EDIT:

the method "defaultFontSized:" seems to be the culprit. If I don't use it, I can see the attributed text. Now the problem is that method should be used, but I don't know what's wrong with it:

-(NSAttributedString*)defaultFontSized:(CGFloat)size{
    NSMutableAttributedString *copy = self.mutableCopy;
    [copy addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"HelveticaNeue" size:size] range:self.range];
    return copy;
}

EDIT 2:

I've solved the problem adding this line before the code for decoding the attributed string:

 str = [NSString stringWithFormat:@"<html><span style=\"font-family: HelveticaNeue; font-size: 16\">%@</span></html>", str ];

I've found this in the link sent from @larme

Aleph72
  • 877
  • 1
  • 13
  • 40
  • `-defaultFontSized`, what's doing that method? I'm wondering if the issue is there, because bold and italic are inside the font attribute... Try without it? Try by not calling it, print the attributedString, then apply it on that attributedString, and print it again to check differences. – Larme Dec 13 '19 at 13:36
  • Yes, that was the problem. I've edited my question to add the code. – Aleph72 Dec 13 '19 at 13:42
  • 1
    Because you are setting the font as `HelveticaNeue` for the whole text. It's not `HelveticaNeue-Italic` or `HelveticaNeue-Bold` nor `HelveticaNeue-BoldItalic`. So you are replacing the bold and/or italic one with the "normal one". – Larme Dec 13 '19 at 13:46
  • I understand now, but the link you've sent is only for Swift and it's a little hard for me to translate it to Obj-C – Aleph72 Dec 13 '19 at 13:51
  • https://stackoverflow.com/questions/19921972/parsing-html-into-nsattributedtext-how-to-set-font ? – Larme Dec 13 '19 at 13:55
  • This last link helped me to solve the problem. If you post it as a solution, I will accept it. Thanks. – Aleph72 Dec 16 '19 at 07:36
  • Mark your question as duplicate of that linked question then – Larme Dec 16 '19 at 07:51

0 Answers0