[英]Call JavaScript from Objective-C in AppDelegate
有什么方法可以從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
如何從inappbrowser中加載的index.html文件調用javascript函數
<!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>
首先:
確保您的Web視圖已經加載了HTML頁面(以防您還需要修改DOM中的某些UI元素,它可能也應該已經呈現。加載本身是異步執行的。這意味着您無法一次實現它處理,但必須等到准備好進行操作為止。
當您通過注入應用程序的start方法調用該函數時,我認為尚未准備好Webview。
而是對iOS應用程序使用Delegate的方法: https : //developer.apple.com/reference/uikit/uiwebviewdelegate
UIWebViewDelegate通知您某些狀態(更改)。 例如:
因此,我建議使用以下委托屬性擴展您的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
您可以在目標C的任何位置調用javascript函數:
NSString *str=@"window['function_name'].apply(window,['param1','param2'])";
[webview evaluateJavaScript:str completionHandler:nil];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.