2015-08-07 9 views
6

Jak mogę wysłać wydarzenie do JavaScript w Swift?Reaguj na Natywne wysyłanie wydarzeń do JavaScript w Swift

Istnieją przykłady kodu Objc, jak wysłać zdarzenie do JavaScript, ale muszę zrobić w szybkim tempie?

#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 
+0

[Zobacz ten post] (https://github.com/facebook/react-native/issues/8714#issuecomment-234437319). –

Odpowiedz

8

Po prostu próbowałem to rozgryźć. To było naprawdę zaskakująco łatwe. Herezje jak to zrobiłem:

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; 

Upewnij się także obejmować kilka importu w pomostowego nagłówka:

#import "RCTBridge.h" 
#import "RCTEventDispatcher.h" 
+0

Wow, słodki. Musiałem zrobić to w Objc i wysłać kod wywołania Objc z Swift –

+0

Mam to działa na kilka innych klas Swift, ale 'self.bridge' jest' nil' kiedy jest używany w moim AppDelegate. Jakieś pomysły? – jamesfzhang

+0

@jamesfzhang czy udało Ci się naprawić self.bridge będąc zerowym w AppDelegate – coldbuffet

Powiązane problemy