1

在我将一些 html 硬编码到我的 UIWebView 函数中后,我得到了要打印的“hello world”文本,但现在我试图将该 HTML 移动到文件系统上其他位置的文件中,并且它没有呈现。

这是我所拥有的:

- (void)viewDidAppear:(BOOL)animated
{   
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"learn" ofType:@"html" inDirectory:@"src/html_files"];

    NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
    [theWebView loadHTMLString:htmlString baseURL:nil];
}

我的 HTML 文件位于我创建的名为 src/html_files 的目录中,该文件名为 learn.html

HTML 没有在屏幕上呈现,我做错了什么?

谢谢!

4

1 回答 1

1

好的,所以Groups只是 Xcode 中的一个构造,用于保持应用程序的资源井井有条。尽管 Xcode 使用了小文件夹图标,但这并不一定意味着它们实际上是(Mac 或 iOS)文件系统上的单独文件夹。

但是,听起来您已将该文件添加为捆绑资源。这也是您发布的代码的样子,但我不得不问一下,以确保。

最有可能的是,唯一错误的是:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"learn" 
                                                     ofType:@"html" 
                                                inDirectory:@"src/html_files"];

应该是这样的:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"learn" 
                                                     ofType:@"html"];

NSBundle 的 Apple 文档中

+ (NSString *)pathForResource:(NSString *)name 
                       ofType:(NSString *)extension 
                  inDirectory:(NSString *)bundlePath

捆绑路径

顶级捆绑目录的路径。这必须是有效路径。例如,要为 Mac 应用程序指定捆绑目录,您可以指定路径 /Applications/MyApp.app。

bundlePath参数并不意味着指定捆绑资源的相对路径。pathForResource:ofType:没有参数的版本bundlePath几乎总是你会使用的。一旦安装了您的应用程序,它将在任何位置找到learn.html文件,并返回该文件的完整路径。您实际上不必担心它是如何嵌套的。它只是一个捆绑资源。

试试看。不过,正如我在评论中所建议的,我始终建议利用error参数进行调试:

NSError* error;
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error: &error];
if (error != nil) {
    NSLog(@"Error with stringWithContentsOfFile: %@", [error localizedDescription]);
}
于 2012-08-14T04:02:56.150 回答