Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use NSURL fileURLWithPath with a fragment?

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?

like image 830
Marius Avatar asked Oct 11 '11 11:10

Marius


2 Answers

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';"];
like image 190
JustSid Avatar answered Sep 27 '22 15:09

JustSid


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];
like image 24
thomax Avatar answered Sep 27 '22 15:09

thomax