Objective C HTML escape/unescape

前端 未结 14 2082
生来不讨喜
生来不讨喜 2020-11-22 16:19

Wondering if there is an easy way to do a simple HTML escape/unescape in Objective C. What I want is something like this psuedo code:

NSString *string = @\"         


        
14条回答
  •  难免孤独
    2020-11-22 16:52

    In iOS 7 you can use NSAttributedString's ability to import HTML to convert HTML entities to an NSString.

    Eg:

    @interface NSAttributedString (HTML)
    + (instancetype)attributedStringWithHTMLString:(NSString *)htmlString;
    @end
    
    @implementation NSAttributedString (HTML)
    + (instancetype)attributedStringWithHTMLString:(NSString *)htmlString
    {
        NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                                   NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    
        NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    
        return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    }
    
    @end
    

    Then in your code when you want to clean up the entities:

    NSString *cleanString = [[NSAttributedString attributedStringWithHTMLString:question.title] string];
    

    This is probably the simplest way, but I don't know how performant it is. You should probably be pretty damn sure the content your "cleaning" doesn't contain any tags or stuff like that because this method will download those images during the HTML to NSAttributedString conversion. :)

提交回复
热议问题