2011-12-03 57 views
1

如何将HTML文件加载到我的应用程序(xcode)中?我正在使用以下代码:如何加载HTML文件?

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]]; 
} 

当我启动应用程序时,我只能看到一个白页。怎么了?

.h文件中:

#import <UIKit/UIKit.h> 

@interface poules : UIViewController { 
    IBOutlet UIWebView *webView; 
} 
@property (nonatomic,retain) UIWebView *webView; 
@end 
+0

你的代码看起来正确,应用程序输出窗格中是否有任何调试消息?并且是通过IB连接到它的UI的webView对象? –

回答

3

这里是我的一个项目的工作示例。我的index.html文件位于资源目​​录中名为Documentation/html的文件夹中。它需要注意的是,这些都是“文件夹引用”,而不是组(因此蓝色图标):

enter image description here

然后将其加载到一个webView

NSString *resourceDir = [[NSBundle mainBundle] resourcePath]; 
NSArray *pathComponents = [NSArray arrayWithObjects:resourceDir, @"Documentation", @"html", @"index.html", nil]; 
NSURL *indexUrl = [NSURL fileURLWithPathComponents:pathComponents]; 
NSURLRequest *req = [NSURLRequest requestWithURL:indexUrl]; 
[webView loadRequest:req]; 
0

尝试loadHTMLString:基本URL:方法

NSString *html=[NSString stringWithContentsOfFile:your_html_path encoding:NSUTF8StringEncoding error:nil]; 

    [webview loadHTMLString:html baseURL:baseURL]; 
0

你可以检查你的web视图是否连接与否的第一件事。

如果是这样,你可以分解你的代码来检查你试图加载的请求有什么问题。

1.为此文件路径创建一个NSString,并检查路径是否被返回。

NSString *urlString = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; 

2.从上面的字符串中创建一个NSURL,并检查url是否正确或为零。

NSURL *url = [NSURL URLFromString:urlString]; 

3.然后创建请求。

NSURLRequest *request = [NSURLRequest requestFromURL:url];