我不熟悉swift编程和FireBase,我已经实现了聊天应用程序,我使用发送方和接收方ID存储消息计数,在接收方获得完美的计数,但当FireBase中添加新计数时,我希望获得新的计数,因为我使用计时器每10秒调用一个函数,我获得完美的计数,但我的问题是计时器持续运行,应用程序挂起且运行缓慢,有时我没有响应,有人能建议我如何每10秒调用一次函数或如何使用计时器吗。
在这里,我尝试了这个代码,
var timer = Timer()
override func viewWillAppear(_ animated: Bool) {
MessageCountingFunction()
}
func MessageCountingFunction(){
//getting count details
keyvalue.removeAllObjects()
countarray.removeAllObjects()
let ref = FIRDatabase.database().reference()
ref.child("CountDetails").child(AuthManager.User.id.value).observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
if let cakeSnapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for cakes in cakeSnapshot {
print(cakes)
if let cakeDictionary = cakes.value as? Dictionary <String, Any> {
print(cakeDictionary)
let count = cakeDictionary["Count"]
let key = cakes.key as String
//your class that takes a key as String and a Dictionary
print(count as Any)
print(key)
self.keyvalue.add(key)
self.countarray.add(count!)
}
}
DispatchQueue.global().sync {
print(self.keyvalue)
print(self.countarray)
self.tableView.reloadData()
}
}
})
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.MessageCountingFunction), userInfo: nil, repeats: true)
}
}