简体   繁体   中英

Objective-C to JavaScript call not happening

I am using Phonegap/Cordova(2.1.0) to create IOS app. I want to call a JavaScript function in index.html file of the Phonegap from an Objective-C function. So, I am creating an instance 'theWebView' of the 'UIWebView' class like below:

Code in AppDelegate.h:

#import <UIKit/UIKit.h>

#import <Cordova/CDVViewController.h>
#import "sqlite3.h"

@interface AppDelegate : NSObject < UIApplicationDelegate > {
    NSString* invokeString;
    
}

@property (nonatomic, strong) IBOutlet UIWebView* theWebView;

Code in AppDelegate.m:

#import "AppDelegate.h"
#import "MainViewController.h"
#import <Cordova/CDVPlugin.h>


@implementation AppDelegate

@synthesize theWebView;

And code for calling JavaScript function is as follows:

// to call javascript function 
    [theWebView stringByEvaluatingJavaScriptFromString:@"myJavascriptFunction()"];

The code is successfully getting built. But, the JavaScript function 'myJavascriptFunction()' defined in script tag of index.html is not getting called. How can I do this?

I am attaching the web-view load code also, which exists in MainViewController.m file. Since, I am using Cordova 2.1.0, separate files exist for ViewController and AppDelegate
classes.

/**
 Called when the webview finishes loading.  This stops the activity view and closes the imageview
 */
- (void)webViewDidFinishLoad:(UIWebView *)theWebView 
{
    NSLog(@"webViewDidFinishLoad function");
    
    // Black base color for background matches the native apps
    theWebView.backgroundColor = [UIColor blackColor];
    
    return [ super webViewDidFinishLoad:theWebView ];
}

- (void)webViewDidStartLoad:(UIWebView *)theWebView 
{
    NSLog(@"webViewDidStartLoad function");    
    return [ super webViewDidStartLoad:theWebView ];
}

/**
 * Fail Loading With Error
 * Error - If the webpage failed to load display an error with the reason.
 */
- (void)webView:(UIWebView *)theWebView didFailLoadWithError:(NSError *)error 
{
    NSLog(@"didFailLoadWithError function");
    return [ super webView:theWebView didFailLoadWithError:error ];
}

/**
 * Start Loading Request
 * This is where most of the magic happens... We take the request(s) and process the response.
 * From here we can redirect links and other protocols to different internal methods.
 */
- (BOOL)webView:(UIWebView *)webView2 
shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSLog(@"shouldStartLoadWithRequest function");
    
    // Intercept custom location change, URL begins with "js-call:"
    if ([[[request URL] absoluteString] hasPrefix:@"js-call:"]) {
        
        // Call the given selector
        [[[UIApplication sharedApplication] delegate] performSelector:NSSelectorFromString(@"resetBadgeCount")];
        
        // Cancel the location change
        return NO;
    }
    
    // Accept this location change
    return YES;
    
}

The code in index.html around the javascript function 'myJavascriptFunction':

<!DOCTYPE html>
<html>
    <head>
        <title>Index Page</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <link rel="stylesheet" href="iui/iui.css" type="text/css" media="all"/>
        <link rel="stylesheet" title="Default" href="iui/t/default/default-theme.css"  type="text/css" media="all"/>
        <link rel="stylesheet" href="iui/t/default/iui-custom.css" type="text/css" media="all"/>
        <script type="text/javascript" src="cordova-2.1.0.js"></script>
        <script type="text/javascript">

            function myJavascriptFunction()
            {
                alert('myJavascriptFunction');
                
                return;
            }
            
            </script>
        
    </head>
    <body id="bd">
    </body>
</html>    

I am attaching the Objective-C code to load the index.html file and then call the JavaScript function :

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"www"];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    NSString *myFile = [path stringByAppendingPathComponent:@"index.html"];
    
    NSLog(@"base url= %@",myFile);
    
    NSData *myFileData = [[NSData alloc] initWithContentsOfFile:myFile];
    NSString* myFileHtml = [[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding];
    
    [theWebView loadHTMLString:myFileHtml baseURL:baseURL];
    
    // to call javascript function 
    [theWebView stringByEvaluatingJavaScriptFromString:@"onDeviceReady()"];

I am thinking problem is with the last line.

I don't think that you have problem with this code. Here everything looks ok, but you should check that myJavascriptFunction() that you are calling if it is working ok. You can try maybe from browser with JavaScript console and see if it is going to work when called manually.

For example code for myJavascriptFunction that works for me is:

        function myJavascriptFunction()
        {
            window.location = "http://www.google.com/";
        }

While alert code is not showing any alert and specially not UIAlertView .

I stand corrected here regarding alerts, UIAlertView is displayed on Javascript alert event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM