开发者

load local HTML file when link is clicked in WebView

开发者 https://www.devze.com 2023-01-26 05:50 出处:网络
I have a WebView that loads a local HTML file like this: [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@\"test1\" ofType:@\"html\"]is

I have a WebView that loads a local HTML file like this:

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

What I want is to click a link in the test1 local HTML file and then for the webView to load the test2 开发者_运维问答local HTML file.

How can I do this?


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.


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


- (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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消