简体   繁体   English

如何将NSURL fileURLWithPath与片段一起使用?

[英]How do I use NSURL fileURLWithPath with a fragment?

I have an IOS project with html file resources shown in a webview. 我有一个IOS项目,其Web视图中显示了html文件资源。 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. 这些html文件具有与片段相对应的不同部分(例如,index.html#section1,index.html#section2),我想在Webview中加载这些片段。 Unfortunately using [NSURL fileURLWithPath:url] does not work with fragments. 不幸的是,使用[NSURL fileURLWithPath:url]不能用于片段。 The # is converted to %23 in the url, and the file is not found. #在URL中转换为%23 ,但找不到该文件。 If I use the [NSURL URLWithString:url] method, it works, but this method cannot load local resources. 如果我使用[NSURL URLWithString:url]方法,则可以使用,但是此方法无法加载本地资源。

Is there a way to have the webview load the local resource url with the fragment? 有没有办法让Webview加载带有片段的本地资源URL?

正如您已经注意到的那样,这对于文件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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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