ios oc调用html,iOS开发网络篇 —— OC加载HTML代码(示例代码)

html代码

图1

样式一:"

\\"7.jpg\\"/测试内容信息无错

"

样式二:

padding: 0px 4px 0px 0px; text-align: left; margin: 0px 0px 10px;\\">你好

了的好莱坞去任何caef76094b36acaf0accebde76d98d1001e99ce7.jpg%5C%5C%22

图2

eb5220163a694f408835a804c623ac16.jpg

一、情景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 转换成字符串

//将 &lt 等类似的字符转化为HTML中的“

- (NSString *)htmlEntityDecode:(NSString *)string

{

string = [string stringByReplacingOccurrencesOfString:@""" withString:@"\\""];

string = [string stringByReplacingOccurrencesOfString:@"\'" withString:@"\'"];

string = [string stringByReplacingOccurrencesOfString:@"

string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"];

string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"]; // Do this last so that, e.g. @"

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:@"

//找到标签的结束位置

[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库。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值