HTML character decoding in Objective-C / Cocoa Touch

后端 未结 13 1988
我寻月下人不归
我寻月下人不归 2020-11-22 10:24

First of all, I found this: Objective C HTML escape/unescape, but it doesn\'t work for me.

My encoded characters (come from a RSS feed, btw) look like this: &a

13条回答
  •  粉色の甜心
    2020-11-22 11:16

    As of iOS 7, you can decode HTML characters natively by using an NSAttributedString with the NSHTMLTextDocumentType attribute:

    NSString *htmlString = @" & & < > ™ © ♥ ♣ ♠ ♦";
    NSData *stringData = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};
    NSAttributedString *decodedString;
    decodedString = [[NSAttributedString alloc] initWithData:stringData
                                                     options:options
                                          documentAttributes:NULL
                                                       error:NULL];
    

    The decoded attributed string will now be displayed as:  & & < > ™ © ♥ ♣ ♠ ♦.

    Note: This will only work if called on the main thread.

提交回复
热议问题