在AppDelegate中调用Objective-C中的JavaScript

时间:2017-05-16 04:42:57

标签: javascript ios objective-c cordova

有没有办法从Objective-C调用设备令牌?

我刚创建了一个cordova ios项目,因为我只掌握Objective-C的基本知识。它会自动生成AppDelegate.m

@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    self.viewController = [[MainViewController alloc] init];

    NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
    [webView stringByEvaluatingJavaScriptFromString:jsCallBack];  

    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

如何从index.html文件中调用javascript函数,该函数在inappbrowser

中加载
<!DOCTYPE html>
<html>
  <head>
    <title>Device Ready Example</title>
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
           myFunction()
               {
              alert('called');
           }
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }
        // device APIs are available
        //
        function onDeviceReady() {
            // Now safe to use device APIs
        }
        </script>
      </head>
      <body onload="onLoad()">
      </body>
    </html>

2 个答案:

答案 0 :(得分:0)

首先:

确保你的webview已经加载了HTML页面(如果你还需要修改DOM中的某些UI元素,它也可能已经被渲染。加载本身是异步执行的。这意味着你无法实现它在一个单一的过程中,但必须等到它准备好进行操作。

当您在应用程序的start方法中通过注入调用该函数时,我认为webview尚未准备好。

而是使用Delegate的iOS应用程序方法: https://developer.apple.com/reference/uikit/uiwebviewdelegate

UIWebViewDelegate会通知您某些状态(-changes)。 e.g:

所以我建议使用以下委托属性扩展AppDelegate(或创建新委托):

@property (nonatomic) UIWebViewDelegate *webDelegate;

相应地设置webView的委托:

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    self.viewController = [[MainViewController alloc] init];
    // I just used your very own code for this, I think you will have a separate property for this webView ?
    webView.delegate = self;
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

并且还实现了一个webview委托方法(在这种情况下,当webview完成加载时:

@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    ...
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
    [webView stringByEvaluatingJavaScriptFromString:jsCallBack];
}

@end

答案 1 :(得分:0)

您可以在目标C的任何位置调用javascript函数:

NSString *str=@"window['function_name'].apply(window,['param1','param2'])";

[webview evaluateJavaScript:str completionHandler:nil];