简体   繁体   中英

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?

正如您已经注意到的那样,这对于文件URL似乎是不可能的,但是如果您不介意,可以使用一种解决方法:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM