Musthafa
Musthafa

Reputation: 862

How can I call Objective-C methods from JavaScript?

I want to display SQLite Data base content on UIWebView. For that i have a local HTML file. On Body load in html file calling JavaScript Function. Inside the Java Script how to call Objective-c method. how to get Data from Objective c to Java Srcipt.

<html>
    <head>
        <!-- a script inline --> 
        <script language="JavaScript" TYPE="text/javascript">
            <!--
            function myJsFunc() 
            { 

                //here i want to call objective-c methods.

            } 
            // -->
            </script>
        </head>
    <Body Bgcolor=#800000 onload="myJsFunc(); return true;">

        </Body>
</html>

Objective-C code ......

- (void)viewDidLoad
{
        [super viewDidLoad];
        NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"Demo" ofType:@"html"];

    // make a file: URL out of the path
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];
    [myWebView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
    [self.view addSubView:myWebView];
}
-(NSArray*)FetchingDataFromDataBase{

    // Code for retriving data from SQlite data Base, and return NSArray;
    return myArray;
}

Inside the Function myJSFunc(), how can call -(NSArray*)FetchingDataFromDataBase.

Upvotes: 3

Views: 2093

Answers (1)

zolio
zolio

Reputation: 2559

The blog post given by graver explains it how to do it.

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

If you have the above method in your class, this method will be called before a new page is loaded. Only if this method returns YES, the new load request is processed. We use that mechanism to communicate back to the Objective-C functions.

Upvotes: 1

Related Questions