【问题标题】:How to call swift native function from react native?如何从 react native 调用 swift native 函数?
【发布时间】:2019-04-01 10:43:40
【问题描述】:

我有一个 swift 类,我将它暴露给 react-native,在里面我有一个也暴露给 react-native 的函数。现在,当 react native 调用该函数时,它会在内部执行很多操作,但在某个时间点后它会返回一个对象。

现在它将调用一个特定的函数来获取对象。我无法将参数更改为该函数。但是我有另一个功能,我想返回到它以响应本机。我该怎么做。

  func AckCallback(response:APIResponse) -> Void
  {
    print(response)  

  }

对于这个函数,我无法更改参数,因为它已被用于很多地方,但我想将此函数的响应返回给 react-native。如果有人知道这个问题,请告诉我。

  @objc func sendEvent(_ response: APIResponse, callback: (NSObject) -> ()) 
-> Void {

    callback( [[
      "responseCode" : "Working",
      ]] as NSObject)

  }

我只是想知道如何在 AckCallback 中使用这个 sendEvent,或者有没有其他方法可以发送它**

响应:APIResponse

**

反应原生。

【问题讨论】:

    标签: objective-c swift react-native


    【解决方案1】:

    对于第一个创建 Swift 类(例如YourModule.swift

    //
    //  YourModule.swift
    //
    
    @objc(YourModule)
    class YourModule: NSObject {
    
      @objc func callNativeEvent(callback:RCTResponseSenderBlock) 
    -> Void {
    
       // Here you can do your work and pass an object to the callback function.
      // You can save assign a `callback` to the class property (e.g self.eventCallback = callback)
    // and invoke that self.eventCallback after the asynchronous code ol somewhere else
      NSObject *obj = [[NSObject alloc] init]; // your object here
       callback([NSNull(), obj]);
       // or if you want to return an error
       // callback(["Error calling NativeEvent", NSNull()]);
    
      // I'm not sure that RCTResponseSenderBlock works the same as in previous react-native versions. Maybe now you can pass an Object instead of an Array.
      }
    }
    

    创建一个 Bridge 文件(例如YourModuleBridge.m

    //
    //  YourModuleBridge.m
    //
    
    #import <Foundation/Foundation.h>
    #import "UIKit/UIKit.h"
    
    #import <React/RCTBridgeModule.h>
    
    
    @interface RCT_EXTERN_MODULE(YourModule, NSObject)
    
    RCT_EXTERN_METHOD(callNativeEvent:(RCTResponseSenderBlock)callback);
    
    @end
    

    另外,如果您的项目中不存在Bridging-Header 文件,则需要它。

    //
    //  YourModule-Bridging-Header.h
    //
    
    #ifndef YourModule_Bridging_Header_h
    #define YourModule_Bridging_Header_h
    
    #if __has_include("RCTBridgeModule.h")
    #import "RCTBridgeModule.h"
    #else
    #import <React/RCTBridgeModule.h>
    #endif
    
    #endif /* YourModule_Bridging_Header_h */
    

    来自 JS

    import { NativeModules } from 'react-native';
    
    const YourModule = NativeModules.YourModule;
    
    ...
    
    YourModule.callNativeEvent((error, response) => {
      console.log('Error', error, 'Response', response);
    });
    

    【讨论】:

    • 感谢您的帮助,但我有一些注册的回调,这些回调有 3 个函数,基于“callNativeEvent”函数中的活动,它将调用这三个函数中的任何一个。现在我要调用三个函数,并且定义了所有三个定义,我无法更改它,但是我注册的回调可以从中调用任何人,从那里我想向我的反应本机回调返回一些东西。 我尝试了另一种从 swift 文件发送通知的选项,但它给出了错误。 self.bridge.eventDispatcher()?.sendAppEvent(withName: eventName, body: "testing")
    • 您可以尝试从RCTEventEmitter 扩展并调用self.sendEvent(withName: "yourEventName", body: ["key": "value"])。在这种情况下,您需要覆盖 supportedEvents 并返回一个事件名称数组 (["yourEventName"]) 在 JS 中 import { NativeModules, NativeEventEmitter } from ''react-native; const myModuleEvt = new NativeEventEmitter(NativeModules.MyModule); myModuleEvt.addListener('yourEventName', (data) =&gt; console.log(data)) 您可以在这里找到一个 ObjectiveC 示例 facebook.github.io/react-native/docs/…
    • @objc func callNativeEvent(_ callback: RCTResponseSenderBlock) -> Void { 使用最新版swift的请在参数前加下划线
    【解决方案2】:

    在 iOS 项目中创建 2 个文件

    SwiftComponentManager.swift and SwiftComponentManager.m  create these 2 files. 
    

    SwiftComponentManager.swift ->

    @objc(SwiftComponentManager)
    class SwiftComponentManager: NSObject {
    
    @objc func passValueFromReact(_ value : String) {
        debugPrint(" Print Here \(value)")
     }
    }
    

    在 SwiftComponentManager.m 中

    #import <Foundation/Foundation.h>
    
    #import "React/RCTBridgeModule.h"
    @interface RCT_EXTERN_MODULE(SwiftComponentManager, NSObject)
    
      RCT_EXTERN_METHOD(passValueFromReact:(NSString *)value) //Here exported your swift function for React Native 
    @end
    

    从这里开始 React-Native 项目的工作

    现在如何在 React Native 中调用这个 Swift 函数。

    React JS 文件中导入你的 SwiftComponent

    const { SwiftComponentManager } = NativeModules
    

    现在在 JS 文件中用你想要的值调用你的函数

    SwiftComponentManager.passValueFromReact("Hello World")
    

    【讨论】:

    • 我收到错误:TypeError: null is not an object (evaluating 'SwiftComponentManager.passValueFromReact')
    • 它有效,我忘记在右侧面板中检查 Target Membership 中的 m 文件
    猜你喜欢
    • 2016-12-26
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多