我应该如何将 tvOS AppDelegate 的 applicationWillEnterForeground 映射到 javascript 函数?

How should I map tvOS AppDelegate's applicationWillEnterForeground to a javascript function?

我正在关注 Playing Media in a Client-Server App 的 Apple 示例项目。

func executeRemoteMethod(_ methodName: String, completion: @escaping (Bool) -> Void) {
    appController?.evaluate(inJavaScriptContext: { (context: JSContext) in
        let appObject : JSValue = context.objectForKeyedSubscript("App")

        if appObject.hasProperty(methodName) {
            appObject.invokeMethod(methodName, withArguments: [])
        }
        }, completion: completion)
}

该方法在应用程序生命周期事件期间被调用,如下所示:

func applicationWillEnterForeground(_ application: UIApplication) {

    executeRemoteMethod("onWillEnterForeground", completion: { (success: Bool) in
        // ...
    })
}

我想知道它是如何工作的。这是为了让本机 iOS 代码库可以将生命周期事件传递给 Javascript 代码吗?当我放置断点时,我看到 executeRemoteMethod 函数被调用。但我不认为它实际上在做任何事情。我怎样才能将它映射到一个js函数?我必须创建一个新的 js 文件还是只在我的 application.js 文件中创建一个新函数?

感谢阅读本文tutorial。我了解到:

In the block beginning, we first get a reference to our JavaScript “App” object. Then, we test the existence of a property with the method name that was passed to us. If it exists, we invoke the method. Although the current implementation doesn’t pass arguments to the method, we could modify it to do that as well if needed. Finally, the completion block that was passed to us is executed when the execution of the JavaScript method has been completed That similar to how the function is already written inside application.js:

在其教程中,application.js 看起来像这样:

App.onLaunch = function(options) {
    var alert = createAlert("Hello World!", "Welcome to tvOS");
    navigationDocument.pushDocument(alert);
}

App.onWillResignActive = function() {
}

App.onDidEnterBackground = function() {
}

App.onWillEnterForeground = function() {
}

App.onDidBecomeActive = function() {
}

App.onWillTerminate = function() {
}

var createAlert = function(title, description) {
    var alertString = `<?xml version="1.0" encoding="UTF-8" ?>
        <document>
          <alertTemplate>
            <title>${title}</title>
            <description>${description}</description>
          </alertTemplate>
        </document>`

    var parser = new DOMParser();

    var alertDoc = parser.parseFromString(alertString, "application/xml");

    return alertDoc
}

因此,我只需在 application.js 中添加以下内容,然后它就会在 AppDelegates 的 WillEnterForeGround 回调中被调用。

App.onWillEnterForeground = function(options) {
    console.log("something")
}