我需要從我的應用程序資源文件夾加載JavaScript文件。截至目前,它確實從資源中讀取圖像,但由於某些原因,它不會讀取JavaScript。從資源加載JavaScript到UIWebView
如果html文件本身寫入資源中,我已經能夠呈現引用這些javascript的html文檔,但是我想通過設置UIWebView的html來呈現html/js,以便它可以是動態的。
下面是我在做什麼:
NSString * html = @"<!DOCTYPE html><html><head><title>MathJax</title></head><body><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script><script type=\"text/javascript\" src=\"/MathJax/MathJax.js\"></script>$$\\int_x^y f(x) dx$$<img src=\"coffee.png\"></body></html>";
NSString * path = [[NSBundle mainBundle] resourcePath];
path = [path stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString * resourcesPath = [[NSString alloc] initWithFormat:@"file://%@/", path];
[webview loadHTMLString:html baseURL:[NSURL URLWithString:resourcesPath]];
現在,如果我改變的基礎URL到我的服務器也具有所需的文件,它不正確加載。不需要互聯網連接將會很棒。任何幫助表示讚賞! ;)
我發現這個有用讓圖像顯示:iPhone Dev: UIWebView baseUrl to resources in Documents folder not App bundle
編輯:
而不是做字符串替換和URL編碼,我是能夠通過簡單地調用resourceURL獲得圖像在mainBundle上,但仍然沒有JavaScript執行。
NSString * setHtml = @"<!DOCTYPE html><html><head><title>MathJax</title></head><body><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script><script type=\"text/javascript\" src=\"/MathJax/MathJax.js\"></script>$$\\int_x^y f(x) dx$$<img src=\"images/test.png\"></body></html>";
[webview loadHTMLString:setHtml baseURL:[[NSBundle mainBundle] resourceURL]];
編輯
如果你想幫助給這個一杆,我已經通過創建一個示例項目使得它更容易爲您服務!
https://github.com/pyramation/math-test
git clone [email protected]:pyramation/math-test.git
我是有這個問題;解決方案是將JavaScript添加到Copy Bundle Resources構建階段:http://stackoverflow.com/questions/843820/iphone-uiwebview-local-resources-using-javascript-and-handling-onorientationchang/851333#851333 – 2011-10-06 03:13:52