我需要从我的应用程序资源文件夹中加载 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
编辑:
我没有进行字符串替换和 URL 编码,而是通过简单地调用 mainBundle 上的 resourceURL 来获取图像,但仍然没有执行 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