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

前端 未结 4 1823
刺人心
刺人心 2021-01-11 20:16

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

    <
相关标签:
4条回答
  • 2021-01-11 20:45

    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)
    
    0 讨论(0)
  • 2021-01-11 20:46

    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

    0 讨论(0)
  • 2021-01-11 21:01

    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]]]];
    
    0 讨论(0)
  • 2021-01-11 21:06

    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)
    
    0 讨论(0)
提交回复
热议问题