2013-02-12 36 views
1

我在打開我的應用程序時打開Goog​​le的AppDelegate.m文件中有以下代碼。我試圖改變它打開一個.HTML網頁,我複製到我的Xcode項目,但它不工作。我正在使用Xcode 4.5.2。OS X Web視圖應用程序 - 不會加載本地.html網頁

,致力於打開谷歌的代碼是:

@implementation MDAppDelegate 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]; 
    [self.webView.mainFrame loadRequest:request]; 
} 

我試圖將其更改爲(以便它會載入我的test.html文件,我把項目文件夾,但應用程序只是出現空白現)。我錯過了什麼?

@implementation MDAppDelegate 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"test.html"]]; 
    [self.webView.mainFrame loadRequest:request]; 
} 

回答

2

只要你test.html在你的項目的根被複制(請確保它也被複制到您的最終應用程序包,呵呵 - 檢查構建階段?),你可以使用此代碼加載了您的Web視圖:

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]; 
NSURL* fileURL = [NSURL fileURLWithPath:path]; 
NSURLRequest* request = [NSURLRequest requestWithURL:fileURL]; 
[self.webView.mainFrame loadRequest:request]; 
+1

這對我有用。謝謝! – user1822824 2013-02-12 03:21:28

+0

@ user1822824很高興幫助! ;-) – 2013-02-12 03:34:57

+0

有沒有簡單的方法來啓用Web視圖的本地存儲? – user1822824 2013-02-15 00:27:19

1

[NSURL URLWithString:@"test.html"]未創建有效的URL到您的文件。試試看:(它來自iOS項目,但也應該適用於OS X應用程序)。我使用的loadHTMLString:baseURL:代替loadRequest:

NSString* fileName = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]; 
NSString* htmlString = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:NULL]; 
NSURL *baseURL = [[NSBundle mainBundle] bundleURL]; 
[self.webView loadHTMLString:htmlString baseURL:baseURL]; 
+0

如果將test.html複製到我的項目的根目錄中,我將如何引用test.html? – user1822824 2013-02-12 01:33:34

+0

'pathForResource:ofType:'有什麼問題? – Sebastian 2013-02-12 01:35:27

+0

我不認爲我明白你的意思?你包含的代碼如何引用test.html?或者,我是否添加了除了我所擁有的代碼? – user1822824 2013-02-12 01:38:35

0
[NSURL URLWithString:@"test.html"] 

有你的問題。假設你test.html文件在您的應用程序包的資源文件夾,而是執行此操作:

[[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"]; 

一個NSBundle有一些其他方法的情況下,輕鬆地創建URL上面的一個不恰當(例如,如果該文件位於子目錄中)。看看NSBundle reference page瞭解更多信息。

相關問題