如何使用Swift在FireBase数据库中发生更改时获取计数值?

如何使用Swift在FireBase数据库中发生更改时获取计数值?,swift,multithreading,function,firebase,timer,Swift,Multithreading,Function,Firebase,Timer,我是swift编程和FireBase的新手,我已经实现了聊天应用程序,我使用发送方和接收方ID存储消息计数,在接收方完美地获得计数,但当FireBase中添加新计数时,我希望获得新计数,因为我使用计时器每10秒调用一个函数,我完美地获得计数,但我的问题是计时器一直在运行,应用程序挂起且运行缓慢,有时我没有响应,有人能建议我如何每10秒调用一次函数或如何使用计时器吗 在这里,我尝试了这个代码 var timer = Timer() override func viewWillAppear(_ a

我是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)
    }

    }
var timer=timer()
覆盖函数视图将出现(uo动画:Bool){
MessageCountingFunction()
}
func MessageCountingFunction(){
//获取计数详细信息
keyvalue.removeAllObjects()
countarray.removeAllObjects()的
让ref=FIRDatabase.database().reference()
ref.child(“CountDetails”).child(AuthManager.User.id.value).observeSingleEvent(of:FIRDataEventType.value,其中:{(快照))在
如果让cakeSnapshot=snapshot.children.allObjects为?[FIRDataSnapshot]{
在cakeSnapshot吃蛋糕{
印刷品(蛋糕)
如果让cakeDictionary=cakes.value作为字典{
印刷(卡克字典)
让count=cakeDictionary[“count”]
让key=cakes.key作为字符串
//将键作为字符串和字典的类
打印(按任何方式计算)
打印(键)
self.keyvalue.add(键)
self.countarray.add(count!)
}
}
DispatchQueue.global().sync{
打印(self.keyvalue)
打印(self.countarray)
self.tableView.reloadData()
}
}
})
DispatchQueue.main.async{
self.timer=timer.scheduledTimer(时间间隔:10,目标:self,选择器:#选择器(self.MessageCountingFunction),userInfo:nil,repeats:true)
}
}

新消息的json数据结构是:-

  • {“状态”:“已发送”,“发件人”:“ayush”,“时间戳”: 1525760473513}
  • 我们正在维护状态键以检查新邮件。读取后,我们将更新status键的值以读取并查找新消息的已发送状态

    var channelRef: DatabaseReference =   Database.database().reference().child(FIREBASE_CONSULTATION_DBKEY)     
    
    channelRef.child("channelKey").observe(DataEventType.value, with: { (snapshot) -> Void in // 1
            if let channelData = snapshot.value as? Dictionary<String, AnyObject>{ // 2
                let id = snapshot.key
                self.chatMessageArray.removeAll()
                for (key,obj) in channelData{
                   if status == "Sent"{
    
    
                    }
                }
             }
          }
        }
    
    var channelRef:DatabaseReference=Database.Database().reference().child(FIREBASE\u CONSULTATION\u DBKEY)
    channelRef.child(“channelKey”).observe(DataEventType.value),带有:{(snapshot)->Void in//1
    如果让channelData=snapshot.value作为字典{//2
    让id=snapshot.key
    self.chatMessageArray.removeAll()
    用于通道数据中的(键,obj){
    如果状态==“已发送”{
    }
    }
    }
    }
    }
    
    删除计时器并更改观察事件闭包,如FIRDataEventType.ChildAddedCu请更改上述代码..以及我在添加FIRDataEventType.ChildAddCd时调用此函数的位置我没有从数据库中获得任何信息这不是一个解决方案当任何新消息添加到数据库时,您不应该在10秒内调用此方法se您将得到回调,基本上,每当您推送新消息时,您必须添加密钥以保持消息是否为新消息。基本上,您使用的是“observeSingleEvent”因此,它不能作为观察者工作。它只能工作一次。如果您使用observeSingleEvent,一次之后您将不会收到任何回调。对于这一点,我应该添加什么代码很好。但请考虑哪一个是最佳解决方案1.您将每隔10秒询问是否有新消息。2.当新消息出现时,数据库本身将通知您我会来的。(firebase是一个实时数据库)