JavaScript and OC Interaction in iOS

Source: Internet
Author: User

In the development of iOS many times we will deal with UIWebView, many domestic applications are now using UIWebView hybrid programming technology, the most common is the public number of content pages. Some time ago in the public platform related development, found that many applications are using HTML5 and UIWebView to achieve.

Mechanism

Objective-c language calls JavaScript language, is through the UIWebView - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script; method to achieve. This method passes a piece of JavaScript code that needs to be executed to UIWebView and finally gets the execution result.

The JavaScript language calls the Objective-c language, and there is no ready-made API, but there are some ways to achieve that. Specifically, the UIWebView feature is used: all network requests initiated within the UIWebView can be notified via the delegate function.

Example

Here is a simple example of how to call each other, the effect is to click on a link on the interface, and then pop up a dialog box to determine whether the login is successful.

(1) The source code for the example HTML is as follows:

123456789101112          
            <meta http-equiv="content-type" content="text/html;charset=utf-8" />        <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta content="always" name="referrer" /> <title>测试网页</title>  <body> <br /> <a href="devzeng://login?name=zengjing&password=123456">点击链接</a> </body>

(2) UIWebView delegate callback method is:

123456789101112131415161718192021222324          
-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype{Nsurl *url = [request URL];if ([[URL scheme] isequaltostring:@ "Devzeng"]) {//handling JavaScript and Objective-c interaction if ([[[URL host] isequaltostring:@ "login"]) { //Get the parameters above the URL Nsdictionary *params = [self getparams:[url query]]; BOOL status = [self login:[params objectforkey:@ "name"] password:[params objectforkey:@ "password"]; if (status) { //Call JS callback [WebView stringbyevaluatingjavascriptfromstring:@ "alert (' Login succeeded! ')"]; } Else { [WebView stringbyevaluatingjavascriptfromstring:@ ' alert (' Login failed! ') "]; } } return NO; return YES; }

Description

1. Synchronous and asynchronous issues

(1) Objective-c is synchronous when invoking JavaScript code

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

(2) When JavaScript calls Objective-c code, it is asynchronous.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

2, the common JS call

(1) Get page title

NSString *title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];

(2) Get the current URL

NSString *url = [webview stringByEvaluatingJavaScriptFromString:@"document.location.href"];

3. Use of third-party libraries

https://github.com/marcuswestin/WebViewJavascriptBridge

Use case

1. Dynamically zoom all the pictures on the page

The JavaScript scripts are as follows:

123456789101112          
function ResizeImages() {  var myImg, oldWidth;  var maxWidth = 320;  for(i = 0; i < document.images.length; i++) { myImg = document.images[i]; if(myImg.width > maxWidth) { oldWidth = myImg.width; myImg.width = maxWidth; myImg.heith = myImg.height*(maxWidth/oldWidth); } }}

Add the following code to your iOS code:

123456789  
[WebView stringbyevaluatingjavascriptfromstring: "Script.type = ' text/javascript ';" " var myimg,oldwidth; "" var maxwidth=380; "//Scaling factor " for (I=0;i <document.images.length;i++) {"  "myimg = Document.images[i];" " oldwidth = Myimg.width; "  "myimg.width = MaxWidth;"  "Myimg.height = Myimg.height * (maxwidth/oldwidth);"  "}\"; "  "document.getElementsByTagName (' head ') [0].appendchild (script);"]; [webview stringbyevaluatingjavascriptfromstring:@ "resizeimages ();"];     

JavaScript and OC Interaction in iOS

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.