在最近的工程中解析字符串的时候出现了这样的
这些不是标准的HTML字符串 所以我们要先转成带<>的HTML字符串 然后在进行加载
贴上代码
-(NSString *)filterHTML:(NSString *)html { NSScanner * scanner = [NSScanner scannerWithString:html]; NSString * text = nil; while([scanner isAtEnd]==NO) { //找到标签的起始位置 [scanner scanUpToString:@"&" intoString:nil]; //找到标签的结束位置 [scanner scanUpToString:@";" intoString:&text]; //替换字符 html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""]; } // NSString * regEx = @"<([^>]*)>"; // html = [html stringByReplacingOccurrencesOfString:regEx withString:@""]; return html; } //将HTML字符串转化为NSAttributedString富文本字符串 - (NSAttributedString *)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]; } //将 < 等类似的字符转化为HTML中的“<”等 - (NSString *)htmlEntityDecode:(NSString *)string { string = [string stringByReplacingOccurrencesOfString:@""" withString:@"\""]; string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"'"]; string = [string stringByReplacingOccurrencesOfString:@"<" withString:@"<"]; string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"]; string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"]; // Do this last so that, e.g. @"&lt;" goes to @"<" not @"<" return string; }
NSString *str = [[responseObject valueForKey:@"info"] valueForKey:@"content"]; NSLog(@"%@", str); str = [self htmlEntityDecode:str]; NSAttributedString *attributedStr = [self attributedStringWithHTMLString:str]; contentLable.attributedText = attributedStr; [self.webView loadHTMLString:str baseURL:nil];