简体   繁体   中英

Check if NSString is HTML string on non-HTML?

I am using a UITextView to display text on a screen. I also want to display HTML text in the same TextView. What I want is, when the string contains any HTML data then it should be displayed according to HTML formatter otherwise textview should use the font defined by me.

Here is the code I am using to display the HTML text in the textview:

NSString *htmlString = promotion.content;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];     
self.promotionTextView.attributedText = attributedString;

I just want to check if the string that I am receiving in the htmlString contains any html data or not. How I can do that?

I would look for html start/end labels and get the substring between them, something like this:

- (NSString *)htmlFromString:(NSString *)string
{
    NSString *htmlString = nil;

    if([string rangeOfString:@"<html>"].location != NSNotFound && [string rangeOfString:@"</html>"].location != NSNotFound) {

        NSRange firstRange = [string rangeOfString:@"<html>"];
        NSRange secondRange = [string rangeOfString:@"</html>"];

        if(firstRange.location < secondRange.location) {

            NSRange htmlRange = NSMakeRange(firstRange.location, secondRange.location + secondRange.length);
            htmlString = [string substringWithRange:htmlRange];
        }

    }

    return htmlString;
}

I haven't tried it, but it think it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM