Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send parameters to a local file in a UIWebView

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!

like image 273
Hectoret Avatar asked Aug 04 '09 08:08

Hectoret


2 Answers

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];
like image 195
Marjan Avatar answered Oct 05 '22 06:10

Marjan


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];
like image 31
surajz Avatar answered Oct 05 '22 04:10

surajz