Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactNative Swift component: how to set the constructor

I have been working on a ReactNative project for a week now, and I want to make my own Objc/Swift native component.

I followed the official documentation but I find it not that detailed. I can use a callback etc, and I also followed this, but I can't find what I want.

I want to use the constructor init() of my Class, but everytime I compile, the app launches and Xcode throws the following error:

fatal error: use of unimplemented initializer 'init()' for class 'myProject.MyModule'

I've tried many things such as adding @objc in front of init(), but nothing works. I'm kinda lost.

My files (I am using Swift 3):

MyModule.m:

#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(MyModule, NSObject)

RCT_EXTERN_METHOD(aMethod:(RCTResponseSenderBlock)callback)

@end

MyModule.swift:

import Foundation
@objc(MyModule)
class MyModule: NSObject {

  var myFirstString: String = ""

  init(myString: String) {

    self.myFirstString = myString

    super.init()
  }

  @objc func aMethod(_ callback: RCTResponseSenderBlock) -> Void {
    callback([NSNull(), self.myFirstString])
  }
}

MyModule-Bridging-Header.h:

#import <React/RCTBridgeModule.h>
like image 685
Anthony Avatar asked Jan 20 '17 14:01

Anthony


1 Answers

Your module requires main queue setup since it overrides init but doesn't implement requiresMainQueueSetup. In a future release React Native will default to initializing all native modules on a background thread unless explicitly opted-out of. (quoted from RCTLog)

Please add the following code in MyModule.swift in order to fix the issue.

@objc override static func requiresMainQueueSetup() -> Bool {
    return false
}
like image 71
tottomotto Avatar answered Nov 08 '22 10:11

tottomotto