Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load NSURL which contains hash fragment "#" with UIWebView?

Tags:

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 "#"?

like image 751
Forrest Avatar asked Jul 14 '11 10:07

Forrest


3 Answers

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)
like image 100
vagase Avatar answered Nov 04 '22 03:11

vagase


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)
like image 3
newshorts Avatar answered Nov 04 '22 03:11

newshorts


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]]]];
like image 1
mohammad alabid Avatar answered Nov 04 '22 01:11

mohammad alabid