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?

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';"];

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];

Need Your Help

How to hold a Boost upgradable_lock for the lifetime of an object?

c++ boost mutex boost-interprocess

I'm implementing a pair of classes for interprocess communication where one process will be the only writer and there will be many readers. One class handles reading; one handles writing. To prev...

iBeacon: Foreground monitoring interval (didDetermineStateForRegion)

cordova monitoring ibeacon

I want to get an alert call when users enter into a region. I managed to get the "inside" alert immediately when users entered into the region. However, it takes around 20 seconds to get the "outsi...