iOS: UIWebview loadhtmlstring & Local css/js/image resources

本文介绍如何使用UIWebView加载包含本地CSS、JS及图片资源的HTML字符串,并提供了一个具体的示例,展示了如何组织HTML字符串以及设置正确的baseURL。

UIWebView 既可以load by url,还可以load html string。即你可以自己generate html string来用web view显示。load html string 典型的应用是:url所对应的web page内容太多,如果只需要部分的html content,那么可以通过http request获取url的html content,然后只选取需要的部分,然后通过load html string来显示。


自己生成的html,有时无法避免要使用local css, js or image (当然你也可以使用url来链接到网上的css/js/image)。

假设在你的ios app里的resource folder里已经存放了a webpage.css and a test.js,那么你生成的html string应该这样include them

    NSString* htmlHeader=@"<html><head><style type='text/css'>@import url('webpage.css');</style><script type='text/javascript' charset='utf-8' src='test.js'></script></head><body>";

    NSString* htmlBody=@"<p> <img alt=\"dept\"  src=\"https://www6.cityu.edu.hk/sa/images/30May12.jpg\"  /></p>";

    NSString* htmlFooter=@"</body></html>";

    NSString* strHtml=[[NSString alloc] initWithFormat:@"%@%@%@",htmlHeader,htmlBody,htmlFooter];

            

    [webView loadHTMLString:strHtml baseURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] resourcePath] isDirectory: YES]];


注意:

1. baseURL就是你的resource folder path

2. 如果把<script type='text/javascript' charset='utf-8' src='test.js'></script>改成<script type='text/javascript' charset='utf-8' src='test.js' />则无法load js (ref link: http://stackoverflow.com/questions/7840127/uiwebview-loadhtmlstring-not-working-in-ios5

3. 当你在ios project里创建js或者把js添加进来后,by default .js文件默认会被当作代码被compiled (你在build project时就会看到warning),因此你需要将.js files从“compile sources” move to "Copy bundle resources",见下图




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值