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

來源:互聯網
上載者:User

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",見

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.