显然,以编程方式加载 HTML 文件时,文档库与应用程序的 Documents 目录不同。
查看 HTML 中的 BASE 元素,它位于 <head> 元素中:
http://www.w3.org/wiki/HTML/Elements/base
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>This is an example for the <base> element</title>
<base href="http://www.example.com/news/index.html">
</head>
<body>
<p>Visit the <a href="archives.html">archives</a>.</p>
</body>
</html>
要解决这个问题,您需要手动提供一个 Document base url。您尚未发布如何以编程方式加载 index.html 文件的代码,因此我假设您正在使用以下UIWebView
方法:
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
所以现在试试这段代码,看看它是否能解决你的问题:
// Get the app Documents path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
// Add www/index.html to the basepath
NSString *fullFilepath = [basePath stringByAppendingPathComponent:@"www/index.html"];// This must be filled in with your code
// Load the file, assuming it exists
NSError *err;
NSString *html = [NSString stringWithContentsOfFile:fullFilepath encoding:NSUTF8StringEncoding error:&err];
// Load the html string into the web view with the base url
[self.webview loadHTMLString:html baseURL:[NSURL URLWithString:fullFilepath]];
如果这不起作用,请尝试更新从 .zip 文件中获取的 HTML 文件的代码。就像是:
// Get the app Documents path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
// Add www/index.html to the basepath
NSError *err;
NSString *fullFilepath = [basePath stringByAppendingPathComponent:@"www/index.html"];
// Load the file, assuming it exists
NSString *html = [NSString stringWithContentsOfFile:fullFilepath encoding:NSUTF8StringEncoding error:&err];
// Check to ensure base element doesn't already exist
if ([html rangeOfString:@"<base"].location == NSNotFound) {
// HTML doesn't contain a base url tag
// Replace head with head and base tag
NSString *headreplacement = [NSString stringWithFormat:@"<head><base href=\"%@\">", fullFilepath];
html = [html stringByReplacingOccurrencesOfString:@"<head>" withString:headreplacement];
[html writeToFile:fullFilepath atomically:YES encoding:NSUTF8StringEncoding error:&err];
}
// Now the file has a base url tag