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

限于喜欢 提交于 2019-12-06 22:14:13

问题


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


回答1:


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)



回答2:


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)



回答3:


It is not loading in web view because you are using wrong method to create a NSURL object, fileURLWithPath is used for a system path. Use this one -

NSURL *url = [NSURL URLWithString:@"http://mysite.com#page1"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

[webView loadRequest:request];

For more info about NSURL read documentation -

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html




回答4:


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


来源:https://stackoverflow.com/questions/6691495/how-to-load-nsurl-which-contains-hash-fragment-with-uiwebview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!