I have an IOS project with html file resources shown in a webview. These html files have different sections which correspond to fragments (eg, index.html#section1, index.html#section2), which I would like to load in the webview. Unfortunately using [NSURL fileURLWithPath:url]
does not work with fragments. The #
is converted to %23
in the url, and the file is not found. If I use the [NSURL URLWithString:url]
method, it works, but this method cannot load local resources.
Is there a way to have the webview load the local resource url with the fragment?
As you have noticed, this seems to be impossible for file URLs, but you could use a workaround if you don't mind:
[webView stringByEvaluatingJavaScriptFromString:@"window.location.hash = '#section2';"];
It's not obvious how Apple intended this sort of navigation to be triggered. There might be several ways to do it, but this one does the trick for me:
NSURL *url = [NSURL fileURLWithPath:@"/full/path/to/index.html"];
NSString *fragment = @"#section1";
url = [NSURL URLWithString:fragment relativeToURL:url];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With