Realize the interaction between OC and JS

Source: Internet
Author: User

Oc-->js Stringbyevaluatingjavascriptfromstring, whose argument is a nsstring string content is the JS code (this can be a JS function, a JS code or their combination), When the JS function has a return value or a sentence JS code has a value returned can be obtained by stringbyevaluatingjavascriptfromstring return value.

Js-->oc Using the WebView redirection principle (that is, to re-specify the value of Document.location in JS, this is a URL), as long as the custom rules in this URL string to specify the required functions and parameters in OC, and then through the OC in the Shouldstartloadwithreque The St function goes to capture processing requests.


App calls WebView loaded JS method Interfacecalledbyapp, this example passed two parameters-(void) SendMessage: (ID) Sender {    [Self.webview Stringbyevaluatingjavascriptfromstring:[nsstring stringwithformat:@ "Interfacecalledbyapp (\"%@\ ", \"%@\ ")", @ "2", @ "333"];}

JS to the app to pass the value. First implement the UIWebView agent, and then according to the Nsurlrequest URL of the different processing//js in the data will be passed as a URL redirection var tempurl = "The value to be passed"; window.location.href= encodeURI (encodeURI (Tempurl));

WebView Proxy Redirection-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) request Navigationtype: (uiwebviewnavigationtype) navigationtype{    nsstring *requeststring = [[Request URL]  Absolutestring] stringbyreplacingpercentescapesusingencoding:nsutf8stringencoding];    NSLog (@ "should-------");    if ([requeststring hasprefix:@ "url://"]) {        //According to the rules that you define, call OC's method through the value of the string. Here is the output of the string.        NSLog (@ "===%@", requeststring);    }    return YES;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.