iOS开发网络篇 —— OC加载HTML代码
html代码
图1
样式一:"<p><img src=\"/upload/image/20170609/1496978712941664.jpg\" title=\"1496978712941664.jpg\" alt=\"7.jpg\"/>测试内容信息无错</p>" 样式二:<h1 style=\"font-size: 32px; font-weight: bold; border-bottom: 2px solid rgb(204, 204, 204); padding: 0px 4px 0px 0px; text-align: left; margin: 0px 0px 10px;\">你好 <a href=\"https://baidu.com\" target=\"_self\" title=\"五六千可\"> 了的好莱坞去任何</a><img src=\"http://imgsrc.baidu.com/imgad/pic/item/caef76094b36acaf0accebde76d98d1001e99ce7.jpg\"/></h1><p><br/></p>
图2
一、情景1:加载到UILabel上面(转换成富文本即可)
//1.将字符串转化为标准HTML字符串 NSString *str1 = [self htmlEntityDecode:htmlString]; //2.将HTML字符串转换为attributeString NSAttributedString * attributeStr = [self attributedStringWithHTMLString:str1]; //3.使用label加载html字符串并将label添加到view上 self.label.attributedText = attributeStr; [self.label setFrame:CGRectMake(100,100,200,300)]; [self.view addSubview:self.label]; //------html 转换成字符串 //将 < 等类似的字符转化为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. @"<" goes to @"<" not @"<" return string; } //------ 将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]; } //图2 中的样式2 可以会出现显示空白,可以通过去除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:@""]; } return html; }
二、情景2:加载到UIWebView上面(替换html中部分的字符)
//1.将字符串转化为标准HTML字符串,(此处的字符串不是标准的标签的HTML字符串,将字符串转换成标准的HTML字符串,这样才可以进行HTML字符串的加载) NSString *str1 = [self htmlEntityDecode:htmlString];//调用情景1的方法 //2.UIWebView 加载HTML字符串 UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(20, 150, self.view.frame.size.width-20, 400)]; [webView loadHTMLString:str1 baseURL:nil]; [self.view addSubview:webView];
三、缓存html用RNCachingURLProtocol库。
将来的自己,会感谢现在不放弃的自己!