Cot*_*bry 5 javascript event-handling ios swift react-native
我创建了以下类(精简版),继承人对完整文件的引用 https://github.com/cotyembry/CastRemoteNative/blob/7e74dbc56f037cc61241f6ece24a94d8c52abb32/root/ios/CastRemoteNative/NativeMethods.swift
@objc(NativeMethods)
class NativeMethods: RCTEventEmitter {
@objc(sendEventToJSFromJS)
func sendEventToJSFromJS {
self.emitEvent(eventName: "test", body: "bodyTestString")
}
func emitEvent(eventName: String: body: Any) {
self.sendEvent(withName: eventName, body: body)
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用emitEvent类似下面的方法时,这完美地工作并触发我的javascript代码中的回调监听器,它是来自https://github.com/cotyembry/CastRemoteNative/blob/7e74dbc56f037cc61241f6ece24a94d8c52abb32/root/js/Components/的修改后的片段
ChromecastDevicesModal.js
从JavaScript方面来看
import {
NativeModules,
NativeEventEmitter
} from 'react-native'
//here I bring in the swift class to use inside javascript
var NativeMethods = NativeModules.NativeMethods;
//create an event emitter to use to listen for the native events when they occur
this.eventEmitter = new NativeEventEmitter(NativeMethods);
//listen for the event once it sends
this.subscription = this.eventEmitter.addListener('test', (body) => { console.log('in test event listener callback', body)});
NativeMethods.sendEventToJSFromJS() //call the native method written in swift
Run Code Online (Sandbox Code Playgroud)
我只是sendEventToJSFromJS在javascript按下按钮调用该方法
再次,这工作,console.log('in test event listener callback', body)代码工作,并在JavaScript方面运行
我的问题,这不起作用:
如果我在定义类后在swift文件中执行以下操作,则无效:
var nativeMethodsInstance = nativeMethods()
nativeMethodsInstance.sendEventToJSFromSwift()
Run Code Online (Sandbox Code Playgroud)
为什么?因为抛出以下错误:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'bridge is not set. This is probably because you've explicitly synthesized the bridge in NativeMethods, even though it's inherited from RCTEventEmitter.'
Run Code Online (Sandbox Code Playgroud)
因此,在创建instanceNativeMethods 时,与之相比......有什么区别?
有关其他信息:
当我在.h和.m文件而不是.swift文件中编写这些相同的代码片段时,Objective-C获得相同的桥接未设置问题
我发现在本机代码中打印错误消息的位置,但它只有变量
_bridge
Run Code Online (Sandbox Code Playgroud)
并检查是否是 nil
这个错误来自的文件是:
RCTEventEmitter.h
RCTEventEmitter.c
Run Code Online (Sandbox Code Playgroud)
这是RCTEventEmitter.c的完整片段
- (void)sendEventWithName:(NSString *)eventName body:(id)body
{
RCTAssert(_bridge != nil, @"bridge is not set. This is probably because you've "
"explicitly synthesized the bridge in %@, even though it's inherited "
"from RCTEventEmitter.", [self class]);
if (RCT_DEBUG && ![[self supportedEvents] containsObject:eventName]) {
RCTLogError(@"`%@` is not a supported event type for %@. Supported events are: `%@`",
eventName, [self class], [[self supportedEvents] componentsJoinedByString:@"`, `"]);
}
if (_listenerCount > 0) {
[_bridge enqueueJSCall:@"RCTDeviceEventEmitter"
method:@"emit"
args:body ? @[eventName, body] : @[eventName]
completion:NULL];
} else {
RCTLogWarn(@"Sending `%@` with no listeners registered.", eventName);
}
}
Run Code Online (Sandbox Code Playgroud)
这个_bridge值在哪里被设置以及它是如何设置的,所以我可以知道,在它失败的情况下如何设置它
我在RCTEventEmitter.h中也发现了以下内容
@property (nonatomic, weak) RCTBridge *bridge;
Run Code Online (Sandbox Code Playgroud)
在给出的错误中,它提到桥在RCTEventEmitter中继承,所以这可能是属性的weak部分问题bridge?
或者我是否需要改变策略,以便我一起完成这项工作?
我知道这可能与我没有完全理解的关系
@synthesize bridge = _bridge;
Run Code Online (Sandbox Code Playgroud)
部分代码和混合的所有语言都没有帮助很多...
这真的很难,所以任何帮助都会非常感激!非常感谢你的时间
这是项目历史代码代表上述问题代码的完整项目的链接(因为我已经对项目进行了更改):
https://github.com/cotyembry/CastRemoteNative/tree/7e74dbc56f037cc61241f6ece24a94d8c52abb32
我想到了
警告:此解决方案使用已弃用的方法反应本机方法 - 我无法弄清楚如何“正确”继承RCTEventEmitter并发送事件......每次我尝试_bridge最终都会是nil
确保 Swift 桥接到 Objective C(如果您使用 swift 将事件发送到 javascript)
不要创建导出的 Native 模块的实例(无论它们是用 Swift 还是 Objective C 编写的)
让 React Native 的底层实现执行此操作,并且对于每个需要发送事件的类,将特定的 Native 类目标 C 实现代码或 Swift 代码(本机模块)导出到 React-Native。这使得 javascript 能够监听事件
var publicBridgeHelperInstance = PublicBridgeHelper() //instantiate the the objective c class from inside the .swift file to use later when needing to get a reference to the bridge to send an event to javascript written in react native
@objc(DeviceManager) //export swift module to objective c
class DeviceManager: NSObject {
@objc(deviceDidComeOnline:) //expose the function to objective c
public func deviceDidComeOnline(_ device: GCKDevice) {
//imagine this deviceDidComeOnline function gets called from something from the Native code (totally independent of javascript) - honestly this could be called from a native button click as well just to test it works...
//emit an event to a javascript function that is a in react native Component listening for the event like so:
//1. get a reference to the bridge to send an event through from Native to Javascript in React Native (here is where my custom code comes in to get this to actually work)
let rnBridge = publicBridgeHelperInstance.getBridge() //this gets the bridge that is stored in the AppDelegate.m file that was set from the `rootView.bridge` variable (more on this later)
//(if you want to print the bridge here to make sure it is not `nil` go ahead:
print("rnBridge = \(rnBridge)")
//2. actually send the event through the eventDispatcher
rnBridge?.eventDispatcher().sendAppEvent(withName: "test", body: "testBody data!!!")
}
}
Run Code Online (Sandbox Code Playgroud)
输入AppDelegate.h(除了文件中已有的代码)
#import "YourProjectsBridgingHeaderToMakeThisCodeAvailableInSwift.h" //replace this with your actual header you created when creating a swift file (google it if you dont know how to bridge swift to objective c)
@interface PublicBridgeHelper: NSObject
-(RCTBridge*)getBridge;
@end
Run Code Online (Sandbox Code Playgroud)
in AppDelegate.mput(除了文件中已有的代码之外)
#import <React/RCTRootView.h>
RCTBridge *rnBridgeFromRootView;
@implementation PublicBridgeHelper //this is created to SIMPLY return rnBridgeFromRootView defined above over to my Swift class when actually sending the event to javascript that defines a react native Component
-(RCTBridge*)getBridge {
NSLog(@"rnBridgeFromRootView = @%@", rnBridgeFromRootView);
return rnBridgeFromRootView;
}
Run Code Online (Sandbox Code Playgroud)
重要- 还要确保将以下代码行添加到 Objective C .h 的桥接标头中,以使此PublicBridgeHelper定义可在 .swift 代码中使用
#import "AppDelegate.h"
Run Code Online (Sandbox Code Playgroud)
现在向您展示如何设置 AppDelegate.m 中使用的 rnBridgeFromRootView 变量(在将事件发送到 javascript 之前返回并在 .swift 代码中使用)
打开AppDelegate.m并在方法体中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... }
Run Code Online (Sandbox Code Playgroud)
rootView在实例化变量的代码行之后包含以下内容
即在可能看起来像这样的行之后
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"YourProjecNameProbably" initialProperties:nil launchOptions:launchOptions];
Run Code Online (Sandbox Code Playgroud)
添加:
rnBridgeFromRootView = rootView.bridge //set the bridge to be exposed and returned later and used by the swift class
Run Code Online (Sandbox Code Playgroud)
现在解释publicBridgeHelperInstance.getBridge().swift 文件中的部分
publicBridgeHelper是一个目标 c 类的实例,它允许 swift 类能够获取对 React Native 桥的引用
如果您在阅读本文后仍然无法理解我的答案,我制作了一个视频,您可以在这里观看:
https://www.youtube.com/watch?v=GZj-Vm9cQIg&t=9s
| 归档时间: |
|
| 查看次数: |
1921 次 |
| 最近记录: |