How to load NSURL which contains hash fragment “#” with UIWebView

nsurl

Given a local URL address like index.html

Now I need to use UIWebView to load it in iPad. I followed these steps:

  1. Create NSURL

    NSURL *url = [NSURL fileURLWithPath:@"http://mysite.com#page1"];
    
  2. Load with UIWebView for local HTML/JS/CSS etc

    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    

But it doesn't work, because "#" is converted to "%23", so the URL string is

http://mysite.com%23page1

My question is, how to fix this auto-conversion issue and let UIWebView access the URL which contains the hash fragment "#"?

Best Answer

User URLWithString to append fragment to your url, like this:

*NSURL *url = [NSURL fileURLWithPath:htmlFilePath];
url = [NSURL URLWithString:[NSString stringWithFormat:@"#%@", @"yourFragmentHere"] relativeToURL:url];*

Hope it will help :)


EDIT: Swift 3 version:

var url = URL(fileURLWithPath: htmlFilePath)
url = URL(string: "#yourFragmentHere", relativeTo: url)
Related Topic