到目前为止,tvOS
支持两种制作电视应用程序的方式,TVML和UIKit,并且没有官方提到如何将TVML (基本上是XML)用户界面与应用程序逻辑和I/O (如回放、流媒体、iCloud持久化等)的本机对应部分混合在一起。
那么,在一个新的tvOS
应用中混合使用TVML
和UIKit
的最佳解决方案是什么呢?
在下面的文章中,我尝试了一个解决方案,根据苹果论坛上的代码片段和关于JavaScriptCore到ObjC/Swift绑定的相关问题进行了改编。这是你的Swift项目中的一个简单的包装类。
import UIKit
import TVMLKit
@objc protocol MyJSClass : JSExport {
func getItem(key:String) -> String?
func setItem(key:String, data:String)
}
class MyClass: NSObject, MyJSClass {
func getItem(key: String) -> String? {
return "String value"
}
func setItem(key: String, data: String) {
print("Set key:\(key) value:\(data)")
}
}
委托必须符合TVApplicationControllerDelegate
typealias TVApplicationDelegate = AppDelegate
extension TVApplicationDelegate : TVApplicationControllerDelegate {
func appController(appController: TVApplicationController, evaluateAppJavaScriptInContext jsContext: JSContext) {
let myClass: MyClass = MyClass();
jsContext.setObject(myClass, forKeyedSubscript: "objectwrapper");
}
func appController(appController: TVApplicationController, didFailWithError error: NSError) {
let title = "Error Launching Application"
let message = error.localizedDescription
let alertController = UIAlertController(title: title, message: message, preferredStyle:.Alert ) self.appController?.navigationController.presentViewController(alertController, animated: true, completion: { () -> Void in
})
}
func appController(appController: TVApplicationController, didStopWithOptions options: [String : AnyObject]?) {
}
func appController(appController: TVApplicationController, didFinishLaunchingWithOptions options: [String : AnyObject]?) {
}
}
在这一点上,javascript非常简单,就像。看一下带有命名参数的方法,您将需要更改javascript计数器部分方法名称:
App.onLaunch = function(options) {
var text = objectwrapper.getItem()
// keep an eye here, the method name it changes when you have named parameters, you need camel case for parameters:
objectwrapper.setItemData("test", "value")
}
App. onExit = function() {
console.log('App finished');
}
现在,假设您有一个非常复杂的js接口要导出,如下所示
@protocol MXMJSProtocol<JSExport>
- (void)boot:(JSValue *)status network:(JSValue*)network user:(JSValue*)c3;
- (NSString*)getVersion;
@end
@interface MXMJSObject : NSObject<MXMJSProtocol>
@end
@implementation MXMJSObject
- (NSString*)getVersion {
return @"0.0.1";
}
你可以这样做
JSExportAs(boot,
- (void)boot:(JSValue *)status network:(JSValue*)network user:(JSValue*)c3 );
此时,在JS计数器部分中,您将不会执行camel案例:
objectwrapper.bootNetworkUser(statusChanged,networkChanged,userChanged)
但你要做的是:
objectwrapper.boot(statusChanged,networkChanged,userChanged)
最后,再看一下这个接口:
- (void)boot:(JSValue *)status network:(JSValue*)network user:(JSValue*)c3;
传入的JSValue*值。是在ObjC/Swift
和JavaScriptCore
之间传递完成处理程序的一种方法。此时,在本机代码中,所有调用都使用参数:
dispatch_async(dispatch_get_main_queue(), ^{
NSNumber *state = [NSNumber numberWithInteger:status];
[networkChanged.context[@"setTimeout"]
callWithArguments:@[networkChanged, @0, state]];
});
在我的调查结果中,我已经看到,如果不在主线程和异步上分派,MainThread将挂起。因此,我将调用javascript "setTimeout“调用,该调用调用完成处理程序回调。
所以我在这里使用的方法是:
javascript
JSExportAs
来获取带有命名参数的方法,并避免将dispatch_async
上使用javascript函数来完成处理程序,可能会调用setTimeout 0-在JavaScript端延迟,以避免UI冻结。更新为了更清楚,我更新了这个问题。我正在寻找一种桥接TVML
和UIKit
的技术解决方案,以便
JavaScriptCode
JavaScriptCore
到ObjectiveC
的正确桥梁,反之亦然当从Objective-C
调用JavaScriptCode
时,
发布于 2015-11-07 02:58:12
此WWDC Video说明如何在JavaScript和Obj-C之间进行通信
下面是我从Swift到JavaScript的通信方式:
//when pushAlertInJS() is called, pushAlert(title, description) will be called in JavaScript.
func pushAlertInJS(){
//allows us to access the javascript context
appController!.evaluateInJavaScriptContext({(evaluation: JSContext) -> Void in
//get a handle on the "pushAlert" method that you've implemented in JavaScript
let pushAlert = evaluation.objectForKeyedSubscript("pushAlert")
//Call your JavaScript method with an array of arguments
pushAlert.callWithArguments(["Login Failed", "Incorrect Username or Password"])
}, completion: {(Bool) -> Void in
//evaluation block finished running
})
}
下面是我如何从JavaScript到Swift进行通信(它需要在Swift中进行一些设置):
//call this method once after setting up your appController.
func createSwiftPrint(){
//allows us to access the javascript context
appController?.evaluateInJavaScriptContext({(evaluation: JSContext) -> Void in
//this is the block that will be called when javascript calls swiftPrint(str)
let swiftPrintBlock : @convention(block) (String) -> Void = {
(str : String) -> Void in
//prints the string passed in from javascript
print(str)
}
//this creates a function in the javascript context called "swiftPrint".
//calling swiftPrint(str) in javascript will call the block we created above.
evaluation.setObject(unsafeBitCast(swiftPrintBlock, AnyObject.self), forKeyedSubscript: "swiftPrint" as (NSCopying & NSObjectProtocol)?)
}, completion: {(Bool) -> Void in
//evaluation block finished running
})
}
更新对于那些想知道Javascript端的"pushAlert“是什么样子的人,我将分享一个用application.js实现的示例
var pushAlert = function(title, description){
var alert = createAlert(title, description);
alert.addEventListener("select", Presenter.load.bind(Presenter));
navigationDocument.pushDocument(alert);
}
// This convenience funnction returns an alert template, which can be used to present errors to the user.
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
}
发布于 2015-10-27 13:34:40
你引发了一个想法worked...almost. .。一旦显示了本机视图,到目前为止还没有简单的方法可以将基于TVML的视图推送到导航堆栈上。我现在所做的是:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.appController?.navigationController.popViewControllerAnimated(true)
dispatch_async(dispatch_get_main_queue()) {
tvmlContext!.evaluateScript("showTVMLView()")
}
JavaScript端的...then:
function showTVMLView() {setTimeout(function(){_showTVMLView();}, 100);}
function _showTVMLView() {//push the next document onto the stack}
这似乎是将执行从主线程移到JSVirtualMachine线程并避免UI锁定的最干净的方法。请注意,我必须至少弹出当前的本机视图控制器,否则它将被发送一个致命的选择器。
https://stackoverflow.com/questions/33081565
复制相似问题