Turn: Realize the simple 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.

?
12345 //APP调用webView加载的JS中的方法interfaceCalledByAPP,此例传入了两个参数- (void)sendMessage:(id)sender {    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"interfaceCalledByAPP(\"%@\",\"%@\")", @"2",@"333"]];}

?
1234 //JS向APP传值。首先实现UIWebView的代理,然后根据NSURLRequest的URL进行不同处理//JS中的将要传递的数据作为URL重定向var tempurl = "将要传递的值";window.location.href= encodeURI(encodeURI(tempurl));

?
1234567891011 //webView的代理相应重定向- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    NSString *requestString = [[[request URL]  absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSLog(@"should-------");    if ([requestString hasPrefix:@"url://"]) {        //根据自己定义的规则,通过字符串的值,调用OC的方法。这里就输出一下字符串了。        NSLog(@"===%@",requestString);    }    return YES;}

Turn: Realize the simple interaction between OC and JS

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.