I want to load a html page from a file, and append a hash tag to it. Is this possible?
I have tried
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"someFile" ofType:@"html"];
NSURL *fileUrl = [NSURL fileURLWithPath:[filePath stringByAppendingFormat:@"#hashtag"]];
[self.webView loadRequest:[NSURLRequest requestWithURL:fileUrl]];
NSLog(@"fileUrl = %@, reachable? %d", fileUrl, [fileUrl checkResourceIsReachableAndReturnError:nil]);
but this tries to look for the file someFile.html%23hashtag
, which can't be found. Is there a way to add the hash after the NSURL
object is created?
I've also tried loading the file into a string and using loadHTMLString
:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"someFile" ofType:@"html"];
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:fileContents baseURL:[NSURL URLWithString:@"http://someFile.html#hashtag"]];
Here the hash tag does work, but my javascript references inside the html don't work. A follow on question from this approach would be, how do I reference javascript files from html loaded in as a string in a UIWebView, ie, what is the base url?
A hack I can think of is to just put all my javascript files inline in the html and load it as a string, but I'm thinking there must be a better way!
This is how I do it in my code. I append the hashmark to the NSString, then I turn it into an NSURL using fileURLWithPath. Then I replace all instances of %23 back into a #. Its all explained in the code below, but let me know if you have any questions.
I've not tried this but how about loading the file normally without the hashtag and implementing the UIWebViewDelegate with something like this?
References:
In Swift (with WKWebView):
I think you have to add the hash after you create the file URL
Does it work if you change
to something like:
You should be able to intercept the
NSURLRequest
, cast it to aNSMutableURLRequest
, then change the URL as follows. All this would happen inshouldStartLoadWithRequest
. Make sure you set the UIWebView delegate.I haven't run into any cases where the request wasn't mutable, but who knows.
Or you may want to set the hash in the original URL (like you were doing), then replace the first occurrence of
%23
with#
inshouldStartLoadWithRequest
.An addition to @xiang's answer. Below the swift version if you're working with local html files in your app: