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.