本文介绍了使用Firebase同步观察SingleEventOfType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图使用信号量来强制Firebase数据查询的同步,以便我可以检查数据库中已存在的项目。 这是我试图检索快照并检查重复的代码: let sem = dispatch_semaphore_create(0) self.firDB.child(sessions)。observeSingleEventOfType(.Value,withBlock:{snapshot in $ b $ snap = snapshot dispatch_semaphore_signal sem)}) //信号从不被声明 dispatch_semaphore_wait(sem,DISPATCH_TIME_FOREVER) var isDuplicate:Bool repeat { sID = genCode() isDuplicate = snap.hasChild(sID)} isDuplicate 在这种情况下,我需要等待快照在 isDuplicate 循环之前返回,但是信号永远不会从 observeSingleEventOfType block。 任何建议都非常感谢。 解决方案 完成处理程序。 func findUniqueId :($ unique_id:String) - >()){ self.firDB.child(sessions)。observeSingleEventOfType(.Value,withBlock:{snapshot in var sID = self.genCode() while snapshot.hasChild(sID){ sID = self.genCode()} completion(uniqueId:sID)})} $ / code> 然后你就可以实现你期望的结果了 $ find $ {code $> findUniqueId(){(uniqueId:String)in //只有在findUniqueId触发完成(sID)时才会调用它... print(uniqueId) //继续您的逻辑... } I am trying to use a semaphore to force synchronisation of a Firebase data query so that I can check for an existing item already in the database. This is the code I have tried to retrieve a snapshot and check for duplicate: let sem = dispatch_semaphore_create(0) self.firDB.child("sessions").observeSingleEventOfType(.Value, withBlock: { snapshot in snap = snapshot dispatch_semaphore_signal(sem) } ) // semaphore is never asserted dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) var isDuplicate : Bool repeat { sID = genCode() isDuplicate = snap.hasChild(sID) } while isDuplicateIn this case I need to wait for a snapshot to return before the isDuplicate loop, but the semaphore is never fired from the observeSingleEventOfType block.Any suggestions greatly appreciated. 解决方案 You might be intersted in using a completion handler.func findUniqueId(completion:(uniqueId:String)->()) { self.firDB.child("sessions").observeSingleEventOfType(.Value, withBlock: { snapshot in var sID = self.genCode() while snapshot.hasChild(sID) { sID = self.genCode() } completion(uniqueId:sID) })}Then you will achieve what you are expecting withfindUniqueId(){ (uniqueId:String) in // this will only be called when findUniqueId trigger completion(sID)... print(uniqueId) // proceed with you logic...} 这篇关于使用Firebase同步观察SingleEventOfType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-26 16:13