我需要从我的应用程序资源文件夹加载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