JS (javascript) interacts with OC (objective-c)

Source: Internet
Author: User



In essence, the communication interaction between OC and JS is to send the message, that is, the function call, iOS7 after the official release of the JavaScriptCore framework is very convenient for us to call each other. In the past, we could only achieve it through the UIWebView uiwebviewdelegate Protocol.


 
(BOOL) webView:(uiwebview *) webView shouldstartloadwithrequest:(nsurlrequest *) request Navigationtype:( Uiwebviewnavigationtype) navigationtype; 


Or


 
(void) webviewdidstartload:(uiwebview *) webView; 
  • 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 JS code has a value return 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.
One JS call oc


JS calls iOS in two different cases


JS inside the direct call method

JS inside by Object Call method

JS inside the direct call method
 
-(void) webViewDidStartLoad: (UIWebView *) webView {

     // First create a JSContext object (here get the jscontext through the key of the current webView)
     JSContext * context = [webView valueForKeyPath: @ "documentView.webView.mainFrame.javaScriptContext"];
      // Where getCurrentUser is the method name of js, which is assigned to a block which contains iOS code
     context [@ "getCurrentUser"] = ^ () {
     // Write OC code in block
         return [[NSUserDefaults standardUserDefaults] objectForKey: @ "MYJSANDOC"];
     };
     context [@ "encodeParam"] = ^ () {
         NSArray * args = [JSContext currentArguments];
         NSString * param = [NSString stringWithFormat: @ "% @", args [0]];
         NSString * result = [[[YXBaseRequestManager alloc] init] encryptUseAES: param key: @ "1% 7jhs # Zjasd & tr *"];
         return result;
     };

} 
JS inside by Object Call method


In this method we need to use theJSExport
JSExportis a protocol, after the custom protocol, inside of the declaration variables and so on JS open, we can Call.



First we want to customize a protocol, add header files#import <JavaScriptCore/JavaScriptCore.h>, inherit fromNSObject


 
#import <Foundation / Foundation.h>
#import <JavaScriptCore / JavaScriptCore.h>
  
// First create a protocol that implements the JSExport protocol
@protocol JSObjectText <JSExport>
  
// Here we test the situation of several parameters
-(void) JSObjectTextPush;
  
@end
  
// Let's create a class that implements the above protocol
@interface JSObject: NSObject <JSObjectText>
  
@end 


implemented in. m


 
#import "JSObjectText.h"
  
@implementation JSObjectText
  
// Store the key locally. After the call, check if the key exists to indicate whether the native method is used.
-(void) JSObjectTextPush
{
     [[NSUserDefaults standardUserDefaults] objectForKey: @ "MYJSANDOC"];
}

@end 


Called after Weibview loading is complete


 
-(void) webViewDidFinishLoad: (UIWebView *) webView
{
     // Call this method after the webpage is loaded
      
     // First create a JSContext object (here get the jscontext through the key of the current webView)
     JSContext * context = [webView valueForKeyPath: @ "documentView.webView.mainFrame.javaScriptContext"];
      
     // In the second case, js is called through an object, we assume that there is an object testobject in js that calls the method
     // First create the object of our newly created class and assign it to the object of js
      
     JSObjectText * text = [JSObjectText new];
     context [@ "testobject"] = text;
      
     // Similarly, we also simulated the js calling method in the way just now
     NSString * [email protected] "testobject.JSObjectTextPush ()";
     [context evaluateScript: jsStr];
 
      
} 
Two OC Call JS


The method is very simple, after loading webview, by clicking the event, or return value, callstringByEvaluatingJavaScriptFromStringto implement the call JS code


 
/ *
  * Click event
  * Call javaScript method postStr () and get the return value
  * Output the return value to the console
  * /
-(void) ocFromJs: (id) sender
{
     NSString * str = [self.webview stringByEvaluatingJavaScriptFromString: @ "postStr ();"];
     NSLog (@ "JS return value:% @", str);
} 


JS (javascript) interacts with OC (objective-c)


Related Article

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.