代码之家  ›  专栏  ›  技术社区  ›  Eniya Sri

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

  •  0
  • Eniya Sri  · 技术社区  · 8 年前

    我不熟悉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)
        }
    
        }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Ayush Yadav    8 年前

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

    1. {“状态”:“已发送”,“发件人”:“ayush”,“时间戳”: 1525760473513}

    我们正在维护状态键以检查新邮件。读取后,我们将更新状态键的值以读取并查找新邮件的发送状态。

    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"{
    
    
                    }
                }
             }
          }
        }
    
    推荐文章