在DocumentsWeb目录中打开UIWebview时,ios-css和js在html文件中无法链接

前端之家收集整理的这篇文章主要介绍了在DocumentsWeb目录中打开UIWebview时,ios-css和js在html文件中无法链接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在ios的Documents目录中有我的www文件夹的结构

  1. Documents
  2. --www
  3. --index.html
  4. --js
  5. --script.js
  6. --css
  7. --style.css

我的index.html文件引用脚本和样式文件,如下所示:

请注意,文件和目录结构是在应用程序启动后从远程下载和解压缩的zip文件中创建的.因此,这不是由于Xcode文件夹组与应用程序包的Documents子文件夹混淆而导致的问题.

它在浏览器中运行时工作正常但在以编程方式在UIWebview中加载index.html时,脚本和样式不起作用.同时索引文件本身加载完美.

当我在index.html文件中提供脚本和css的完整路径时,它对我来说很好.

为什么相对路径不起作用?

提前致谢.

最佳答案
显然,以编程方式加载HTML文件时,文档库与应用程序的Documents目录不同.

查看HTML中的BASE元素,它位于< head>内.元件:

http://www.w3.org/wiki/HTML/Elements/base

  1. Meta charset="utf-8">

解决此问题,您将手动提供文档基本URL.您还没有发布代码如何以编程方式加载index.html文件,因此我假设您正在使用以下UIWebView方法

  1. - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL

所以现在试试这段代码,看看它是否解决了你的问题:

  1. // Get the app Documents path
  2. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  3. NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  4. // Add www/index.html to the basepath
  5. NSString *fullFilepath = [basePath stringByAppendingPathComponent:@"www/index.html"];// This must be filled in with your code
  6. // Load the file,assuming it exists
  7. NSError *err;
  8. NSString *html = [NSString stringWithContentsOfFile:fullFilepath encoding:NSUTF8StringEncoding error:&err];
  9. // Load the html string into the web view with the base url
  10. [self.webview loadHTMLString:html baseURL:[NSURL URLWithString:fullFilepath]];

如果这不起作用,请尝试更新从.zip文件获取的HTML文件代码.就像是:

  1. // Get the app Documents path
  2. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,YES);
  3. NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  4. // Add www/index.html to the basepath
  5. NSError *err;
  6. NSString *fullFilepath = [basePath stringByAppendingPathComponent:@"www/index.html"];
  7. // Load the file,assuming it exists
  8. NSString *html = [NSString stringWithContentsOfFile:fullFilepath encoding:NSUTF8StringEncoding error:&err];
  9. // Check to ensure base element doesn't already exist
  10. if ([html rangeOfString:@"

猜你在找的HTML相关文章