2010-11-18 145 views
1

我有加载一个本地HTML文件,像这样的的WebView本地HTML文件:负载当链接被点击的WebView

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test1" ofType:@"html"]isDirectory:NO]]]; 

我要的是点击test1的本地HTML文件的链接,然后webView加载test2本地HTML文件。

我该怎么做?

回答

1

像在一个普通的网页。让测试1中的链接指向test2。

+0

你能告诉我怎样写链接吗? – StefanHanotin 2010-11-18 12:56:59

+0

我使用上面的答案得到它。 – StefanHanotin 2010-11-18 13:04:46

+0

如果我的回答对你有帮助,为什么这个标记被接受?您应该将解决问题的答案标记为已接受。 – Jasarien 2010-11-18 13:07:47

6

而不是加载请求,使用- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL方法。

创建从本地HTML文件中像这样的NSString

NSError *error = nil; 
NSString *html = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"test1" ofType:@"html"] encoding:NSUTF8StringEncoding error:&error]; 

然后将其加载到web视图,就像这样:

[webview loadHTMLString:html baseURL:[NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"test1" ofType:@"html"]]]; 
在HTML文件中

然后,当你链接到其他网页,只需使用它们的文件名,如<a href="test2.html">Test 2</a>,它会在同一个webview中加载页面而不会出现任何问题。

+0

你肯定有正确的答案加载本地html文件!感谢您的提示:)我会给你一个+1 – Unikorn 2010-11-19 06:41:29

+0

如果我使用你的代码,我得到以下错误:“不兼容指针类型发送'NSString *'到类型'NSURL *'的参数'” 最新错误? – MJB 2012-04-30 22:56:33

+0

我的不好,我从内存中键入了代码,并且忘记了baseURL带了一个NSURL或者忘记了那个pathForRes没有返回一个NSURL。其中之一。应该现在就好了。 – Jasarien 2012-05-01 11:06:53

1
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [webview loadHTMLString:[self htmlString] baseURL:[self baseURL]]; 
} 
- (NSURL *)baseURL{ 
    NSString *htmlpath = [[NSBundle mainBundle] pathForResource:@"webpage" ofType:@"html"]; 
    return [[[NSURL alloc] initFileURLWithPath:htmlpath] autorelease]; 
} 

- (NSString *)htmlString{ 
    NSError *error = nil; 
    NSString *html = [[[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"webpage" ofType:@"html"] 
                encoding:NSUTF8StringEncoding 
                 error:&error] autorelease]; 
    return html; 
}