Swift 4.2 升级后将 Swift 类桥接到 React Native
Posted
技术标签:
【中文标题】Swift 4.2 升级后将 Swift 类桥接到 React Native【英文标题】:Bridging Swift class to React Native after Swift 4.2 upgrade 【发布时间】:2019-09-03 18:26:47 【问题描述】:在 Swift 3.0 中,我有以下 Swift 类
import Foundation
@objc(NetworkManager)
class NetworkManager: NSObject
init(...)
...
deinit
...
func isConnected(resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void
...
还有下面的桥:
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(NetworkManager, NSObject)
_RCT_EXTERN_REMAP_METHOD(isConnected, isConnectedWithResolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject, NO)
@end
升级到 Swift 4.2 后,这开始以isConnnectedWithResolver:rejecter is not a recognized Objective-C method.
失败
环顾四周,发现这个问题:Got "is not a recognized Objective-C method" when bridging Swift to React-Native, 这个代码示例:https://github.com/bigali/StringToHash/blob/master/ios/StringToHash/StringToHash.m
我已将其更改为:
import Foundation
@objc(NetworkManager)
class NetworkManager: NSObject
init(...)
...
deinit
...
func isConnected(_ resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void
...
和:
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(NetworkManager, NSObject)
_RCT_EXTERN_REMAP_METHOD(isConnected, isConnected:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject, NO)
@end
仅将错误消息中的函数名称更改为:
isConnnectedWithResolver:rejecter is not a recognized Objective-C method.
是什么导致了这个问题?为什么其他问题中概述的解决方案不起作用?我该如何解决这个问题?
【问题讨论】:
你能将RCTPromiseRejectBlock
声明为@objc吗?
我该怎么做?我无法摆脱@escapingn,因为我确实需要承诺(这是一个 JS 承诺)才能在对 isConnected 的调用中幸存下来?
【参考方案1】:
您应该将 eventEmitter 导入到。 把它放到你的头桥文件和你的objective-c文件中
#import "React/RCTEventEmitter.h"
【讨论】:
以上是关于Swift 4.2 升级后将 Swift 类桥接到 React Native的主要内容,如果未能解决你的问题,请参考以下文章
Swift:IBAction 在单击按钮后将图像放入 UIImageView