views:

976

answers:

5

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!

+2  A: 

No, unfortunately not.

You can, however, get around this by setting variables and calling functions / methods in JavaScript using the UIWebView:stringByEvaluatingJavaScriptFromString:

groundhog
I've got a javascript function defined in the local html file. I can load that file, but, how could I call a javascript function inside that file? I need an example.
Hectoret
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"myJavascriptFunction(%f);", 1.0f]];
rpetrich
Did you get that to work? Does the myJavascriptFunction function get called? In my code it doesn't... how can I check for sure if the call it's being done?
Hectoret
+2  A: 

You are loading the HTML from your own bundle which implies you have full control over it. Why not just parameterize the HTML with the fields you want. You could easily add in some hidden input fields that your javascript could then access. Say your HTML looked like this:

<body>
<form>
Static Field 1: <input type="text" name="field1"><br>
Static Field 2: <input type="text" name="field2"><br>
%@
</form>
</body>

Now just read this data into a string and format the %@ with some hidden fields like this:

NSString *input = @"<input type=\"hidden\" name=\"field3\"><br>";
NSString *formatted = [NSString stringWithFormat:html, input];

Then call -loadHTMLString: in the webview.

[webView loadHTMLString:formatted baseURL:nil];

Is there any reason you couldn't do it that way. Now your javascript can grab the value of the hidden input field with a call to:

document.getElementsByName('field3')[0].value;
Matt Long
+2  A: 

You can insert in your local html-file a javascript to parse the GET-request

<script language="javascript">
function getget(name) {
     var q = document.location.search;
     var i = q.indexOf(name + '=');

     if (i == -1) {
      return false;
     }

     var r = q.substr(i + name.length + 1, q.length - i - name.length - 1);

     i = r.indexOf('&');

     if (i != -1) {
      r = r.substr(0, i);
     }

     return r.replace(/\+/g, ' ');
    }
</script>

Use getget('parameter_name') to get the parameter from request string.

Pavel Yakimenko
A: 

Then call -loadHTMLString: in the webview.

I believe he was avoiding using loadHTMLString instead of loadRequest because it breaks back and forward buttons of the UIWebView

jpmartineau