Given a local URL address like index.html
Now I need to use UIWebView
to load it in iPad. I followed these steps:
Create NSURL
NSURL *url = [NSURL fileURLWithPath:@"http://mysite.com#page1"];
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 "#"?
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)
for reference in swift:
let path = NSBundle.mainBundle().pathForResource("index", ofType: "html", inDirectory: "web")
var url = NSURL(fileURLWithPath: path!)
url = NSURL(string: "#URL_FRAGMENT", relativeToURL: url!)
let request = NSURLRequest(URL: url!)
self.webView.loadRequest(request)
For swift 3 solution1: You can call this line after webview loaded
webView.stringByEvaluatingJavaScript(fromString: "window.location.href = '#myHashtag'")
solution2: also if you want to load directly use this
webView1.loadRequest(URLRequest(url: URL(string: url! + "#myHashtag")!))
ObjC: solution 1:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"window.location.href = '#myHashtag';"]; }
solution2:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat: @"%@#myHashtag",myURL]]]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With