2011-12-03 61 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];