Submit a form in UIWebView

后端 未结 2 493
耶瑟儿~
耶瑟儿~ 2020-12-29 12:44

I have a form in the UIWebView to interact with a web service, when I submit the form, the data gets sent to a web service and it will return the result to another UIWebView

2条回答
  •  青春惊慌失措
    2020-12-29 13:04

    You can use the

    stringByEvaluatingJavaScriptFromString
    

    function for firing a javascript method from objective c and get a return value from that method.

    For example

    //Calling the getTheUsername in the javascript.
    NSString *userName = [yourWebView stringByEvaluatingJavaScriptFromString:@"getTheUsername()"];
    

    and in javascript

    //Method in javascript
    function getTheUsername()
    {
    return userNameVariable;
    }
    

    And I doubt that here you may wanna do vice-versa (Call obj-c method from javascript). This cannot be done directly here is the work around.

    Set a UIWebViewDelegate, and implement the method webView:shouldStartLoadWithRequest:navigationType:. In your JavaScript code, navigate to some fake URL that encodes the information you want to pass to your app, like, say: window.location = "someLink://yourApp/form_Submitted:param1:param2:param3"; In your delegate method, look for these fake URLs, extract the information you need, take whatever action is appropriate, and return NO to cancel the navigation.

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
        NSLog(@"%@",[[request URL] query]);
    
        return YES;
    }
    

提交回复
热议问题