【问题标题】:Send Event from Native to Ionic将事件从 Native 发送到 Ionic
【发布时间】:2019-03-07 17:41:12
【问题描述】:

我正在使用 Ionic/Cordova 插件来监视数据集,并希望在本机 api 触发事件时调用我的 typescript 类中的函数。到目前为止我所拥有的是:(打字稿文件)

this.platform.ready().then(() =>{
window.plugins.plugin.startFileWatch("Path", (success) =>{console.log("Succes")}, (error) => {Console.log("ERROR"}))
}

然后在插件中的java脚本中

startFileWatch: function( path, succesCB, errorCB){
  exec(succesCB, errorCB, "Class", "startFileWatch", [path]);
}

并在 swift 中(尽管也欢迎使用 android 解决方案):

    @objc(startFileWatch:)
    func startFileWatch(command:CDVInvokedUrlCommand){
           //bit pseudo here      
           something.addListener{
                self?.commandDelage.send(result, callbackID: command.callbackID)
}
    }

但这并没有奏效

【问题讨论】:

    标签: cordova ionic-framework events callback


    【解决方案1】:

    您的 TS 和 JS 脚本看起来不错。您缺少的是,您没有为将来的触发器保存回调。要触发从 Native 到 TS 的动态事件,您需要有一个侦听器,它实际上会在 Native 层注册回调。然后这个回调用于将事件推送到 TS 层。

        // Android
    
        protected static CallbackContext eventTriggerObj = null;
        .....
        .....
    
        private boolean registerForEvents ( final CallbackContext callbackContext )
        {
            eventTriggerObj = callbackContext;
            return true;
        }
    
    
      // iOS ( Obj C )
    
      @property ( nonatomic, retain ) NSString * eventTriggerObj ;  
      .....
      .....
    
      - ( void ) registerForEvents :( CDVInvokedUrlCommand * ) command
        {
            self.eventTriggerObj = command.callbackId;
            CDVPluginResult * pluginResult = [ CDVPluginResult 
                 resultWithStatus:CDVCommandStatus_OK ];
             [ pluginResult setKeepCallbackAsBool:true ];
             [ self.commandDelegate sendPluginResult:pluginResult 
             callbackId:command.callbackId ];
        }
    
        // Swift Code (3+)
        private var eventTriggerObj : String
    
        void registerForEvent(command : CDVInvokedUrlCommand){
             self.eventTriggerObj = command.callbackId
             let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: ["Message"])
             pluginResult?.keepCallback = true
             self?.commandDelegate.send(pluginResult, callbackId: self?.eventTriggerObj)
        }
    

    现在使用回调对象 eventTriggerObj 将动态事件发送到 TS 层。

    【讨论】:

    • Thnx,您是否也有 Swift (3) 代码?
    • 不。仅用 Obj C 进行过实验。但是从您上面的代码中,我可以解释为您需要将“command.callbackID”存储为类变量,以便稍后在您想向 TS 发送触发器时访问它。
    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多