Cuelogic Blog Icon
Cuelogic Career Icon
Home > Blog > All > Bridging between Objective C and Javascript

Bridging between Objective C and Javascript

In this section i will write about the bridging between the native Objective-C code with the web portion(JavaScript/HTML) code. We will use UIWebView for loading app with linking URL & we can have our own iOS feature included in it .So in this blog i will describe how to call native Objective C- method from particular button from webview and vice versa.

JSblayer

Call JavaScript Function from objective C

In your Javascript files add following piece of code:

 function myJavascriptFunction () {
        // Do whatever your want!
        }
       // 

And in your Objective-C code Call Javascript function using this line of code

 [webViewObject stringByEvaluatingJavaScriptFromString:@"myJavascriptFunction()"];

Call Objective C method from Javascript

To call Objective C function from JS we have to register a UIWebViewDelegate on your web view and ‘catch-and-immediatly-cancel ‘ a location change done in javascript.

 // In Objective-C
-(void) viewDidLoad
{    
    webView = [[UIWebView alloc] init];
    // Register the UIWebViewDelegate in order to shouldStartLoadWithRequest to be called (next function)
    webView.delegate = self;  
    
}
// This function is called on all location change :
  - (BOOL)webView:(UIWebView *)webView2 
          shouldStartLoadWithRequest:(NSURLRequest *)request 
          navigationType:(UIWebViewNavigationType)navigationType {
    
    // Intercept custom location change, URL begins with "js-call:"
    if ([[[request URL] absoluteString] hasPrefix:@"js-call:"]) {
      
      // Extract the selector name from the URL
      NSArray *components = [requestString componentsSeparatedByString:@":"];
      NSString *function = [components objectAtIndex:1];
      
      // Call the given selector
      [self performSelector:NSSelectorFromString(functionName)];
      
      // Cancel the location change
      return NO;
    }
    
    // Accept this location change
    return YES;
    
  }

- (void)myObjectiveCFunction {
    
    // Do whatever you want!
   
  }

Now in your javascript simply do this to call your objective-c function:

window.location = "js-call:myObjectiveCFunction";

You have to create some JavaScript code, attach it to the event you want to monitor and call the correct window.location call to be then intercepted.