I'm working on a native iPhone app. I am able to load a local file index.html into a UIWebView:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];
The web loads fine. Now, I would like to load the web with some parameters, in the same way one types this in the browser: URL?var1=myValue&var2=myValue2
So I can get those values inside the javascript of the html file. Is there any way to send parameters to a local html file?
Thanks!
The best and really working answer, only in objC (remember to retain your folder structure - copy files into xcode using "Create Folder References for any added folders")
NSString *path = [[NSBundle mainBundle]
pathForResource:@"YOUR-HTML-FILE"
ofType:@"html"
inDirectory:@"YOUR-FOLDER" ];
NSURL *url = [NSURL fileURLWithPath:path];
NSString *theAbsoluteURLString = [url absoluteString];
NSString *queryString = @"?var=1232123232";
NSString *absoluteURLwithQueryString = [theAbsoluteURLString stringByAppendingString: queryString];
NSURL *finalURL = [NSURL URLWithString: absoluteURLwithQueryString];
NSURLRequest *request = [NSURLRequest requestWithURL:finalURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:(NSTimeInterval)10.0 ];
[web loadRequest:request];
Marjan's way is the proper way of making it work.
As my friend Terence pointed it out, the trick is to use absolute file uri (file://) string when creating the url from string properly. This way ? character does not get encoded, and webview can load the file properly.
[NSURL URLWithString: @"file://localhost/Users/sj/Library/Application%20Support/iPhone%20Simulator/5.0/Applications/../PrintingWebView.app/final.html?slide=2"];
Or use URLWithString:relativeToURL method
NSURL *relativeURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSURL *u = [NSURL URLWithString:@"html/index.html?site=2" relativeToURL:relativeURL];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With