load local HTML file when link is clicked in WebView

徘徊边缘 提交于 2019-12-01 12:08:28

Like in a regular webpage. Let the link in test 1 point to test2.

Instead of loading a request, use the - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL method.

Create an NSString from the local HTML file like this:

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

Then load it into the webview, like this:

[webview loadHTMLString:html baseURL:[NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"test1" ofType:@"html"]]];

Then in your HTML file when you link to other pages, just use their filename, like <a href="test2.html">Test 2</a> and it would load the page in the same webview without any issues.

- (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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!