Skip to content

Instantly share code, notes, and snippets.

@harveyconnor
Created May 26, 2020 01:13
Show Gist options
  • Save harveyconnor/7b0e778effaae302f512485c18881569 to your computer and use it in GitHub Desktop.
Save harveyconnor/7b0e778effaae302f512485c18881569 to your computer and use it in GitHub Desktop.
React Native Swift Module Singleton Pattern with Events Example

React Native Swift Module Singleton Pattern

If you are reading this tutorial please be aware that this is for advanced users that require a singleton pattern in their RN native module and some documentation detail is left out intentionally.

For the sake of this tutorial we will be using TestManager as our class.

Instructions

  1. First of all you need to setup a swift class with a bridging header, in Xcode it will generate this for you upon creating a Swift file.
  2. Create your swift class with the @objc directive.
  3. Create a second class that has a static export of the class in singleton.
  4. Follow the files below for a boilerplat example.

See files for more info

#import "React/RCTBridgeModule.h"
#import "React/RCTEventEmitter.h"
@interface RCT_EXTERN_MODULE(RNTestManager, RCTEventEmitter)
RCT_EXTERN_METHOD(sendTest)
@end
@objc
class RNTestManager: RCTEventEmitter {
private var manager: TestManager
private var hasListeners = false
override init() {
super.init()
manager = TestManager.shared
manager.testEventCallback = testEventCallback
}
@objc
func sendTest() {
manager.sendTest()
}
func testEventCallback(_ message: String) {
if hasListeners {
sendEvent(withName: "testEvent", body: message)
}
}
override func startObserving() {
hasListeners = true
}
override func stopObserving() {
hasListeners = false
}
override func supportedEvents() -> [String]! {
return [
"testEvent"
]
}
override class func requiresMainQueueSetup() -> Bool {
return true
}
}
class TestManager: NSObject {
static let shared = TestManager()
var testEventCallback: ((String) -> Void)?
func sendTest() {
testEventCallback?("This is a test")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment