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