objective-c - 如何从 react native 调用 swift native 函数?

标签 objective-c swift react-native

我有一个 swift 类,我将其暴露给 react-native,其中我有一个函数也暴露给 react-native。现在,当 React Native 调用该函数时,它会在内部做很多这样的事情,但在某个时间点后它会返回一个对象。

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

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

  }

对于这个函数我不能改变参数,因为它已经用了很多地方,但是我想把这个函数的响应返回给 react-native。如果有人知道这个问题,请告诉我。

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

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

  }

我只想知道如何在 AckCallback 中使用这个 sendEvent,或者是否有任何其他方式发送那个 **

response: APIResponse

**

react native 。

最佳答案

对于第一次创建 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);
});

关于objective-c - 如何从 react native 调用 swift native 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55453240/

相关文章:

swift - 实现具有不同关联类型的协议(protocol)

Android Application Emulator 在 React Native 上不断停止

javascript - 对于 React Native 中的 navigator.geolocation, native 模块不能为 null

swift - 缺少带有默认参数的声明

ios - 将一个变量从一个 View Controller 传递到另一个 View Controller

react-native - react native 更改按钮颜色无法正常工作

iphone - 如何使用zbar sdk知道结果类型(条形码或qrcode)?

objective-c - 是否可以定义一个符合协议(protocol)的Class类型的属性?

objective-c - iOS: "Flip-Clock"动画 - 怎么办?

ios - 我如何在 obj-c 的 block 中通过引用发送参数