How to bridge React Native Promise to Swift

后端 未结 3 1413
慢半拍i
慢半拍i 2021-02-12 14:46

Hi fellow software enthousiasts,

I am currently working on a React native project for which I need to add some logic which has been written in swift. I am able to trigge

相关标签:
3条回答
  • 2021-02-12 15:03

    Taken from the answers at Got "is not a recognized Objective-C method" when bridging Swift to React-Native; the fact that it doesn't work, is because of the difference in the first argument labels.

    To make it work with your initial code you should write the first argument of your Swift to be without a name, like this:

    @objc
    func loginWithEmail(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) -> Void {
        //   the trick  ^
        resolve("This method is no longer troublesome")
    }
    
    0 讨论(0)
  • 2021-02-12 15:11

    Adding so that the complete solution is shown

    .m - note that the resolve parameter is not "named"

    RCT_EXTERN_METHOD(loginWithEmail: (RCTPromiseResolveBlock)resolve
                                      rejecter:(RCTPromiseRejectBlock)reject)
    

    .swift - same as @Koen

    @objc func loginWithEmail(_ resolve: @escaping RCTPromiseResolveBlock,
                                rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void {}
    
    0 讨论(0)
  • 2021-02-12 15:11

    I did eventually come up with a solution. It is not exactly like React native people intended it I believe, but it works. So i can continue and maybe someone else is set on the right track with my solution. Although, please post the way it is supposed to be.

    So I decided to start with the Objective-C way first. So I created a .h file for my module.

    MyLoginBridge.h

    #import <React/RCTBridgeModule.h>
    
    @interface MyLoginBridge : NSObject <RCTBridgeModule>
    @end
    

    Then alter the .m file

    #import "MyLoginBridge.h"
    #import "MyProject-Swift.h" // Include the swift header manually
    
    @implementation MyLoginBridge
    
    RCT_EXPORT_MODULE(MyCustomLoginJSName);
    
    RCT_EXPORT_METHOD(loginWithEmail:(RCTPromiseResolveBlock)resolve   rejecter:(RCTPromiseRejectBlock)reject)
    {
        // Manually init the module and call swift function
        MyLoginModule* module = [[MyLoginModule alloc] init];
        [module loginWithEmailWithResolver:resolve rejecter:reject];
    }
    
    @end
    

    The swift file and the bridging header remained the same. This works.

    0 讨论(0)
提交回复
热议问题