计时器在本机反应本机组件中不起作用 [英] Timer doesn't work in native react-native component
问题描述
在我的 JavaScript 中,我正在一些 swift 代码上调用 start
方法:
In my JavaScript, I'm calling a start
method on some swift code:
import {NativeModules} from "react-native";
// somewhere in JS
NativeModules.MyTestClass.start();
// somewhere else I'm listening for events from the swift code
const myModule = new NativeEventEmitter(NativeModules.MyTestClass);
const subscription = myModule.addListener("testEvent", message => {
console.log(message);
});
Swift 代码:
import Foundation
@objc(MyTestClass)
class MyTestClass: RCTEventEmitter {
let testEventName = "testEvent"
override func supportedEvents() -> [String]! {
return [testEventName]
}
@objc func start() -> Void {
let timer = Timer.scheduledTimer(
timeInterval: 0.1,
target: self,
selector: #selector(self.update),
userInfo: nil,
repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}
@objc func update() {
print("test")
self.sendToJs(message: "test")
}
@objc private func sendToJs(message: String) -> Void {
self.sendEvent(withName: testEventName, body: message)
}
}
...它启动一个计时器,然后在本例中重复向我侦听事件的 JavaScript 代码发送相同的消息.
...which starts up a timer and then, in this example, repeatedly sends the same message to my JavaScript code listening for the event.
问题:即使将计时器添加到主运行循环中,也永远不会调用 update
方法,如 这个答案.
Problem: The update
method is never called even when adding the timer to the main run loop as outlined in this answer.
我在这里犯了一个简单的错误吗?我是 swift 的新手.
Is there a simple mistake I'm making here? I'm new to swift.
如果没有,我将不得不将计时器移动到 JS,然后重复调用数据的 swift 代码......我宁愿不这样做,因为在我的真实场景中,计时器发回数据是有条件的,但我猜猜这样做还不错...
If not, I'll have to move the timer to JS then repeatedly call the swift code for the data... I'd rather not do that because in my real scenario the timer sending back data is conditional, but I guess doing that is not too bad...
推荐答案
想通了.由于某种原因需要在主线程上设置定时器,不需要将其添加到主运行循环中.
Figured it out. The timer needs to be setup on the main thread for some reason and no need to add it to the main run loop.
这可以通过将 start
函数更改为以下内容来完成:
This can be done by changing the start
function to the following:
@objc func start() -> Void {
DispatchQueue.main.async(execute: {
Timer.scheduledTimer(
timeInterval: 0.1,
target: self,
selector: #selector(self.update),
userInfo: nil,
repeats: true)
})
}
这篇关于计时器在本机反应本机组件中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!