How to call an objective-c method from JavaScript

As the title says, call an objective-c method from Javascript/HTML file. Let’s talk about the Javascript side, we have to request a new URL with a specific string and this is done in Javascript side by

function communicateWithObjectiveC () {

window.location = “js-call:myObjectiveCFunction:” + names;

}

This will make the UIWebView call a delegate method, which is :

– (BOOL)webView:(UIWebView *)webView

shouldStartLoadWithRequest:(NSURLRequest *)request

navigationType:(UIWebViewNavigationType)navigationType {

In this method, we can search the new request string by using:

if ([[[request URL] absoluteString] hasPrefix:@”js-call:”]) {

after that, we call the method that we want by:

[self performSelector:NSSelectorFromString(function)];

If we wrap up the previous codes (Objective-c side), the method will look like this:

– (BOOL)webView:(UIWebView *)webView

shouldStartLoadWithRequest:(NSURLRequest *)request

navigationType:(UIWebViewNavigationType)navigationType {

// Intercept custom location change, URL begins with “js-call:”

if ([[[request URL] absoluteString] hasPrefix:@”js-call:”]) {

NSString *requestString = [[request URL] absoluteString];

// Extract the selector name from the URL

NSArray *components = [requestString componentsSeparatedByString:@”:”];

if ([[components objectAtIndex:1] isEqualToString:@”myObjectiveCFunction”]) {

NSString *function = [components objectAtIndex:1];

// Call the given selector

[self performSelector:NSSelectorFromString(function)];

}

// Cancel the location change

return NO;

}

// Accept this location change

return YES;

}

That’s it, piece of cake 🙂

If there is any ambiguity, don’t be shy, just ask.

Be tuned for the next Tutorial.

Remove the white background for UIWebview

This is a simple tip for removing the white background for UIWebView.

The problem appear when you load a local html file or a request to display a web page, it takes a couple of millisecond until the white background disappear.

We are fine with it as a developer, but some of the customer may get upset to see it, so i’ve searched for a solution and with some of luck i found it, the solution is simple, you just have to add this piece of code in viewDidLoad to remove the white background


[webView setOpeque:NO];
[webView setBackgroundColor:[UIColor clearColor]];


This is it, the problem is solved.

stay tuned for the next topic.

Mumen Shabaro.