目标c到javascript调用不发生 [英] objective-c to javascript call not happening

查看:114
本文介绍了目标c到javascript调用不发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用phonegap / cordova(2.1.0)来创建IOS应用程序。我想从一个objective-c函数的phonegap的index.html文件中调用一个javascript函数。所以,我创建一个'UIWebView'类的实例theWebView,如下所示:



AppDelegate.h中的代码:

  #import< UIKit / UIKit.h> 

#import< Cordova / CDVViewController.h>
#importsqlite3.h

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

}

@property(非原子,强)IBOutlet UIWebView * theWebView;

AppDelegate.m中的代码:

  #importAppDelegate.h
#importMainViewController.h
#import< Cordova / CDVPlugin.h>


@implementation AppDelegate

@synthesize theWebView;

调用javscript函数的代码如下:

  //调用javascript函数
[theWebView stringByEvaluatingJavaScriptFromString:@myJavascriptFunction()];

代码已成功创建。但是,在index.html的脚本标签中定义的javascript函数myJavascriptFunction()没有被调用。我怎么能这样做。任何帮助是赞赏。



我附加的web视图加载代码,也存在于MainViewController.m文件。因为,我使用cordova 2.1.0,ViewController和AppDelegate

类存在单独的文件。

  / ** 
当webview完成加载时调用。这将停止活动视图并关闭imageview
* /
- (void)webViewDidFinishLoad:(UIWebView *)theWebView
{
NSLog(@webViewDidFinishLoad function);

//背景的黑色基色匹配原生应用程序
theWebView.backgroundColor = [UIColor blackColor];

return [super webViewDidFinishLoad:theWebView];
}

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

/ **
*失败加载错误
*错误 - 如果网页加载失败显示错误的原因。
* /
- (void)webView:(UIWebView *)theWebView didFailLoadWithError:(NSError *)error
{
NSLog(@didFailLoadWithError function);
return [super webView:theWebView didFailLoadWithError:error];
}

/ **
*开始加载请求
*这是大多数魔法发生的地方...我们接受请求并处理响应。
*从这里我们可以将链接和其他协议重定向到不同的内部方法。
* /
- (BOOL)webView:(UIWebView *)webView2
shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

NSLog shouldStartLoadWithRequest function);

//拦截自定义位置更改,URL以js-call:开头
if([[[URL请求] absoluteString] hasPrefix:@js-call:]){

//调用给定的选择器
[[[UIApplication sharedApplication] delegate] performSelector:NSSelectorFromString(@resetBadgeCount)];

//取消位置更改
return NO;
}

//接受此位置更改
return YES;

}

index.html中的代码在javascript函数myJavascriptFunction ':

 <!DOCTYPE html> 
< html>
< head>
< title>索引页< / title>
< meta name =viewportcontent =width = device-width,initial-scale = 1.0,maximum-scale = 1.0,user-scalable = 0/>
< meta name =apple-mobile-web-app-capablecontent =yes/>
< link rel =stylesheethref =iui / iui.csstype =text / cssmedia =all/>
< link rel =stylesheettitle =Defaulthref =iui / t / default / default-theme.csstype =text / cssmedia =all/&
< link rel =stylesheethref =iui / t / default / iui-custom.csstype =text / cssmedia =all/&
< script type =text / javascriptsrc =cordova-2.1.0.js>< / script>
< script type =text / javascript>

function myJavascriptFunction()
{
alert('myJavascriptFunction');

return;
}

< / script>

< / head>
< body id =bd>
< / body>
< / html>

我附加目标c代码加载index.html文件,然后调用javascript函数:

  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];

//调用javascript函数
[theWebView stringByEvaluatingJavaScriptFromString:@onDeviceReady()];

我想的问题是最后一行。

解决方案

我不认为你有这个代码的问题。这里一切看起来确定,但你应该检查 myJavascriptFunction()你正在调用,如果它是正常工作。



对于我的myJavascriptFunction的示例代码是:

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

虽然提醒代码没有显示任何提醒, c $ c> UIAlertView



我在这里纠正警报,UIAlertView显示在Javascript警报事件。 >

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 javscript 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. Any help is appreciated.

I am attaching the web-view load code also, which exists in MainViewController.m file. Since, i am using cordova 2.1.0, seperate 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.

这篇关于目标c到javascript调用不发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆