ios android 发东西,Android、IOS主动发事件给React Native

IOS(Swift版本)

//RNEventEmitter.m

#import

#import

@interface RCT_EXTERN_MODULE(RNEventEmitter, NSObject)

@end

//RNEventEmitter.swift

import Foundation

@objc(RNEventEmitter)

class RNEventEmitter: RCTEventEmitter {

//提供出EventName

override func supportedEvents() -> [String]! {

return ["UnReadMsgCountEvent"]

}

override func startObserving() {

NotificationCenter.default.addObserver(self, selector: #selector(emitEventInternal(_:)), name: NSNotification.Name(rawValue: "event-emitted"), object: nil)

}

override func stopObserving() {

NotificationCenter.default.removeObserver(self)

}

func emitEventInternal(_ notification: NSNotification) {

let eventName: String = notification.userInfo?["eventName"] as! String

print("send event to RN: \(self.bridge) \(eventName) \(notification.userInfo)")

self.sendEvent(withName: eventName, body: notification.userInfo)

}

@objc func notifiyRN(_ eventName: String, parameters: [String: Any] = [:] ) {

var newParams: [String: Any] = parameters

newParams["eventName"] = eventName

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "event-emitted"), object: self, userInfo: newParams)

}

}

import {

NativeEventEmitter,

NativeModules

} from 'react-native'

....

componentDidMount(){

const { RNEventEmitter } = NativeModules

const eventEmitter = new NativeEventEmitter(RNEventEmitter);

this.emitter = eventEmitter.addListener("UnReadMsgCountEvent", (data) => {

console.log("ios 收到通知了:内容是:", data && data.unReadMsgCount)

});

}

componentWillUnmount() {

this.emitter.remove();

}

....

RNEventEmitter().notifiyRN("UnReadMsgCountEvent", parameters: ["unReadMsgCount": number]) })

IOS中使用RCTEventEmitter, 直接调用方法self.sendEvent(..)无效,RN会收不到事件. self.sendEvent(..)底层调用的self.bridge enqueueJSCall.会发现bridge = nil. 这里有个坑. 我们应该使用加载RN自构建的实例. 一种解决办法是在startObserving在给实例添加通知.实际调用发送事件事件时候,触发通知. 另外一种办法实现该类的单例.

Android

WritableMap map = Arguments.createMap();

map.putInt("unReadMsgCount", badgeCount);

getReactInstanceManager().getCurrentReactContext()

.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)

.emit("UnReadMsgCountEvent", map);

import {

DeviceEventEmitter

} from 'react-native'

...

componentDidMount(){

this.emitter = DeviceEventEmitter.addListener("UnReadMsgCountEvent",(data) => {

console.log("android 收到通知了:内容是: ", data && data.unReadMsgCount);

this.updateMailBoxBadge(data)

})

}

componentWillUnmount() {

this.emitter.remove();

}

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值