2012-08-14 63 views
1

我得到的“Hello World”的文本打印后,我硬编码一些HTML送到我的UIWebView的功能,但现在我想的是HTML移动到文件的其他地方在文件系统上,它不是渲染。IOS - 从.html文件打印HTML不是在一个UIWebView工作

以下是我有:

- (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不在屏幕上呈现?

谢谢!

+0

**凡**上的文件系统是这个文件?这是一个捆绑资源,用您的应用程序构建?它是你的应用的**文档**或**缓存**目录中的文件吗?请调试您的应用程序。在分配了htmlFile后停止。使用'NSLog()'显示'htmlFile'的值。然后,越过“htmlString”被分配的行。 'htmlString'的价值是什么?它是'零'吗?我总是推荐使用它的方法的'NSError'参数,并在操作完成后检查它。您正在传递'error:nil',如果发生错误,您不会看到错误。 – Nate 2012-08-14 03:08:07

+0

@Nate我做了一个新的“组”,并把html文件存在。我不确定这意味着它是否在捆绑资源中。我如何在那里添加它?或者我应该在那里添加它?我对这个文件做了什么正确的事情? – GeekedOut 2012-08-14 03:25:31

回答

1

好吧,那么群组只是Xcode中的一个构造,用于保持您的应用程序资源的有序性。尽管Xcode使用小文件夹图标,但并不一定意味着这些文件夹实际上是(Mac或iOS)文件系统上的单独文件夹。

但是,听起来好像您已将该文件添加为捆绑软件资源。这就是你发布的代码的样子,但我必须问,确定。

最有可能的,唯一错的是这个:

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

应该是这个:

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

the Apple documentation for NSBundle

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

bundlePath

The path of a top-level bundle directory. This must be a valid path. For example, to specify the bundle directory for a Mac app, you might specify the path /Applications/MyApp.app.

bundlePath参数并不意味着以指定到捆绑资源的相对路径。不具有bundlePath参数的pathForResource:ofType:版本几乎总是你会使用什么。它会发现learn.html文件是任何一个,一旦安装你的应用程序,以及完整的路径返回到。你不必担心它是如何嵌套的。这只是一个捆绑资源。

给一个尝试。正如我在我的评论所说,虽然,我总是建议进行调试服用error参数的优势:

NSError* error; 
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error: &error]; 
if (error != nil) { 
    NSLog(@"Error with stringWithContentsOfFile: %@", [error localizedDescription]); 
}