my code


call objective-C from JS in UIWebview
by lavecoi

Snippet options

Download: Download snippet as call-objective-c-from-js-in-uiwebview.c.
Copy snippet: For this you need a free my code account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    //This will catch clicked links and location changes made from Javascript, but no other request types
    if (navigationType == UIWebViewNavigationTypeLinkClicked || navigationType == UIWebViewNavigationTypeOther)
        NSURL *URL = [request URL]; //Get the URL
        //The [URL scheme] is the "http" or "ftp" portion, for example
        //so let's make one up that isn't used at all -> "objc"
        if ( [[URL scheme] isEqualToString:@"objc"] ) {
            //The [URL host] is the next part of the link
            //so we can use that like a selector
            NSString *selectorName = [URL host];
            id data = nil;
            NSMutableArray *parameters = [NSMutableArray array];
            if ( ![[URL path] isEqualToString:@""] )
                selectorName =  [NSString stringWithFormat:@"%@:", selectorName];
                parameters = [NSMutableArray arrayWithArray: [[URL path] componentsSeparatedByString:@"/"] ];
                [parameters removeObjectAtIndex:0]; //first object is just a slash "/"
                if ( [parameters count] == 1 ){
                    data = [parameters objectAtIndex:0];
                    data = parameters;
            SEL method = NSSelectorFromString( selectorName );
            if ([functionDelegate respondsToSelector:method])
                //This line may give a warning but that's ok, we are being memory concious
                // See:
                [functionDelegate performSelector:method withObject:data];
            return NO;
    return YES;

Create a free my code account now.

my code is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.