swift - React Native 在 Swift 中向 JavaScript 发送事件

标签 swift react-native

如何在 Swift 中向 JavaScript 发送事件?

有 Objc 代码示例如何将事件发送到 JavaScript,但我需要在 swift 中执行?

#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

@implementation CalendarManager

@synthesize bridge = _bridge;

- (void)calendarEventReminderReceived:(NSNotification *)notification
{
  NSString *eventName = notification.userInfo[@"name"];
  [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
                                               body:@{@"name": eventName}];
}

@end

最佳答案

我只是想自己解决这个问题。这实际上出奇的容易。这是我的做法:

EventTests.m

#import "RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(EventTests, NSObject)

RCT_EXTERN_METHOD( testEvent:(NSString *)eventName )

@end

EventTests.Swift

import UIKit

@objc( EventTests )
class EventTests: NSObject {
    // Swift doesn't have synthesize - just define the variable
    var bridge: RCTBridge!

    @objc func testEvent( eventName: String ) {
        self.bridge.eventDispatcher.sendAppEventWithName( eventName, body: "Woot!" )
    }
}

MyModule.js

var React      = require( 'react-native' );
var EventTests = require( 'NativeModules' ).EventTests;

var {
    Component,
    NativeAppEventEmitter
} = React;

var testEventName = 'test';

class MyModule extends Component {

    constructor( options ) {
        super( options );

        // Register for our test event
        NativeAppEventEmitter.addListener( testEventName, ( body ) => {
            console.log( body );
        });

        // Call objective c function, which will emit our test event
        EventTests.testEvent( testEventName );
    }
}

module.exports = MyModule;

还要确保在桥接 header 中包含一些导入:

#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

关于swift - React Native 在 Swift 中向 JavaScript 发送事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31870775/

相关文章:

swift - URL 验证无法快速工作

node.js - 使用 Expo start 而不是 npm start

ios - React Native 与 Appsee 中的触摸手势问题

javascript - 使用 URL 模式对 native 重定向使用react

json - 有没有比我使用的更好的方法来 "Pretty Print"json 字符串

ios - 避免 View Controller 的多实例创建

ios - 更新数组内结构中的属性

ios - 我们如何知道相册中是否已存在图像?

javascript - 如何在保持数据状态有序的同时保持接收数据?

javascript - 如何使用 jest 测试 void 函数