2

我必须显示一个需要 highcharts.js、jquery.min.js 的 .html 文件才能显示图表。我打算在 UIWebView 中显示 .html 文件。

我看到当文件(即 html、highcharts.js、jquery.min)在 Application Bundle 中时,我可以像这样使用它们——

aPath = [[NSBundle mainBundle] pathForResource:@"htmlfile" ofType:@"html"]; [self.graphWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:aPath isDirectory:NO]]];

在这里,“htmlFile”的来源是这样的 -

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TITLE</title>

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<script type="text/javascript" src="htmlfile.js"></script>
<script type="text/javascript" src="global.js"></script>
</head>
<body>
<div id="wrapper">

<div id="container"></div>    
</div>
</body>
</html>

因此,为了在 UIWebView 中显示内容,我只需要在 Xcode 的 Build Phases 选项卡中将 .html 文件和 .js 文件制作为Bundle Resources 。

问题:

保存在 App 沙盒中的 .html 文件如何显示如上图所示的源文件?

我试过了:

1.我在App SandBox中创建了一个这样的文件夹--

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;

NSString aFolderPath = [(NSString )[paths objectAtIndex:0] stringByAppendingFormat:@"/%@",@"folder"];

if(![[NSFileManager defaultManager] isWritableFileAtPath:aFolderPath]){

[[NSFileManager defaultManager]createDirectoryAtPath:aFolderPath withIntermediateDirectories:NO attributes:nil error:nil]; }

2.然后我像这样从App Bundle中复制了App SandBox中的html,js文件--

NSString *aJs = [[NSBundle mainBundle] pathForResource:@"JSFile" ofType:@"js"];

aJs = [NSString stringWithContentsOfFile:aGlobaljs encoding:NSUTF8StringEncoding error:nil];

NSString *aPath = [(NSString*)[paths objectAtIndex:0] stringByAppendingFormat:@"/folder/%@",@"JSFile.js"];

[aJs writeToFile:aPath atomically:YES encoding:NSUTF8StringEncoding error:nil];

现在所有需要的文件都在名为“文件夹”的沙盒文件夹中,所以,我尝试像这样在 UIWebView 中打开保存的 html 文件——

[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:pathToHtmlFileinDocumentsDic relativeToURL:[NSURL URLWithString:aFolderPath]]]];

这不起作用。

4

2 回答 2

2

您必须将文件保存在您的应用程序资源中,这里的技巧是保持 JavaScript 文件与 HTML 文件的相对链接。添加 html 包时,选择“为任何添加的文件夹创建文件夹引用”。并在代码中像这样调用您的 html 页面:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"Help"];

  NSURL *indexUrl = [NSURL fileURLWithPath:filePath];

您的所有 Html 页面(包括cssimagesjs)都在 Help(或您拥有的任何其他名称)文件夹中。即,它就像在文件夹内维护一个本地静态站点

于 2012-10-31T06:55:06.113 回答
0

您可以在本地启动 http 服务器(例如通过https://github.com/robbiehanson/CocoaHTTPServer)并设置/<appPath>/Documents/yourFolder为服务器根。然后你可以UIWebView NSURL像这样打开:http://localhost:8080/index.html

于 2017-04-10T09:52:41.657 回答