Call Swift code from an Apple TV TVML TVJS JavaScript App

不打扰是莪最后的温柔 提交于 2019-12-13 06:12:36

问题


I have a basic TVML application set up. Currently simple events (such as a button press) are handled via JavaScript (TVJS).

When the user presses a button (provided via TVML template) I'd like some code to run in Swift instead, that manipulates UI elements.

What's the best way to do this?


回答1:


You can use evaluateAppJavaScriptIn method in TVApplicationControllerDelegate as below and write corresponding swift method in it; (swift side)

// MARK: TVApplicationControllerDelegate
func appController(_ appController: TVApplicationController, evaluateAppJavaScriptIn jsContext: JSContext){
    let debug : @convention(block) (String!) -> Void = {
        (string : String!) -> Void in
        #if DEBUG
            print("[log]: \(string!)\n")
        #endif
    }
    jsContext.setObject(unsafeBitCast(debug, to: AnyObject.self), forKeyedSubscript: "debug" as (NSCopying & NSObjectProtocol)!)
}

After that you can call this method from TVJS like this; (js side)

debug('Hello from js to swift...');


来源:https://stackoverflow.com/questions/38187957/call-swift-code-from-an-apple-tv-tvml-tvjs-javascript-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!