【发布时间】:2011-08-09 16:26:51
【问题描述】:
我需要从我的应用资源文件夹中加载 javascript 文件。截至目前,它确实可以很好地从资源中读取图像,但由于某种原因它没有读取 javascripts。
如果 html 文件本身被写入资源,我已经能够呈现引用这些 javascripts 的 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
编辑:
我可以通过简单地调用 mainBundle 上的 resourceURL 来获取图像,而不是进行字符串替换和 URL 编码,但仍然没有执行 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 git@github.com:pyramation/math-test.git
【问题讨论】:
-
我遇到了这个问题;解决方案是将 JavaScript 添加到 Copy Bundle Resources 构建阶段:stackoverflow.com/questions/843820/…
标签: javascript xcode ios resources mathjax