iOS之載入HTML中的特殊字元
阿新 • • 發佈:2019-02-01
在最近的工程中解析字串的時候出現了這樣的
這些不是標準的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];