2015-08-07 8 views
6

Come posso inviare eventi a JavaScript in Swift?Reagire eventi nativi di invio a JavaScript in Swift

Esistono esempi di codice Objc su come inviare un evento su JavaScript, ma è necessario farlo in modo rapido?

#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

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

risposta

8

Stavo solo cercando di capirlo da solo. In realtà era sorprendentemente facile. Ecco come ho fatto:

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; 

Assicuratevi anche di includere alcune importazioni nell'intestazione colmare:

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

Wow, dolce. Ho dovuto farlo in Objc e ho mandato il codice Objc da Swift –

+0

Ho questo lavoro su alcune altre classi Swift ma 'self.bridge' è' nil' quando usato nel mio AppDelegate. Qualche idea? – jamesfzhang

+0

@jamesfzhang sei riuscito a correggere self.bridge essendo nullo in AppDelegate – coldbuffet

Problemi correlati