X0r0N
X0r0N

Reputation: 1934

how do i call objective c code from javascript

i've some javascript code on the webpage in the uiwebview that i want to use to call one of my objective c methods.

i found some code online which i decided to use. but it still doesn't seem to be working. can anyone see where the problem is?

javascript code:

function someMethod() {
window.location = "ios:webToNativeCall";
}

objective c code:

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] absoluteString] hasPrefix:@"ios:"]) {

        // Call the given selector
        [self performSelector:@selector(webToNativeCall)];
        // Cancel the location change
        return NO;
    }
    return YES;
}

-(void)webToNativeCall
{
    //my code here
}

i'm not sure, how to use this method so it might be that i have implemented it incorrectly.

does anyone have any ideas about what could be causing this?

Thanks in advanced.

Upvotes: 0

Views: 294

Answers (2)

Martin
Martin

Reputation: 866

  1. This code looks ok, please check whether delegate for UIWebView is set or not.

  2. Otherwise you can use EasyJSWebView download it from Github, it is easy to use.

Upvotes: 1

Vidhyanand
Vidhyanand

Reputation: 5369

You must have missed to link the delegate.

Either connect the delegate of the webView to the file owner in the .xib file

or

Use Following code

webView = [[UIWebView alloc] init];
webView.delegate = self;

in your viewDidLoad also write below code

[webView stringByEvaluatingJavaScriptFromString:@"yourJavascriptFunction()"];

Hope it helps you...

Upvotes: 0

Related Questions