Firebase查询未按我想要的顺序触发,如何解决此问题?

时间:2018-06-21 22:33:47

标签: swift xcode firebase

在我的iOS应用中,我尝试从Google Firebase中提取字符串以填充数组好友,然后在该数组上进行迭代以使用Markers填充friendsMarkers。我的问题是,因为friends []返回一个空数组,所以fetchFriendsMarkers中的for循环永远不会执行。这是同步问题吗?如果是这样,如何在fetchFriendsMarkers()执行之前确保朋友不为空?

    var ref: DatabaseReference?
    var friends: [String] = []
    var friendsMarkers: [Marker] = []

    private func viewDidLoad(){
            ref = Database.database().reference()
            fetchFriends()
            fetchFriendsMarkers()
    }   

    private func fetchFriends(){
            let query = ref?.child("users").child((currentUser?.uid)!).child("Friends")
            query?.observe(.childAdded, with: { (snapshot) in
                let friend = snapshot.value as? NSDictionary
                let id = friend!["id"] as! String
                self.friends.append(id)
            })
            query?.observe(.childRemoved, with: { (snapshot) in
                let friend = snapshot.value as? NSDictionary
                let id = friend!["id"] as! String
                var index: Int
                for i in self.friends{
                    if i == id{
                        index = self.friends.index(of: i)!
                        self.friends.remove(at: index)
                    }
                }
            })
        }

        private func fetchFriendsMarkers(){
            for friend in self.friends {
                let query1 = ref?.child("user-locations").child(friend)
                query1?.observe(.childAdded, with: { (snapshot) in

                })
                query1?.observe(.childChanged, with: { (snapshot) in

                })
                query1?.observe(.childRemoved, with: { (snapshot) in

                })
            }
        }

1 个答案:

答案 0 :(得分:1)

这些都是异步调用,这就是为什么未调用其他函数的原因。接收数据时,您需要在fetchFriends函数中调用fetchFriendsMarkers,并建议进行以下修改:

private func fetchFriends(){
 let query = ref?.child("users").child((currentUser?.uid)!).child("Friends")
 query?.observe(.childAdded, with: { (snapshot) in
   let friend = snapshot.value as? NSDictionary
   let id = friend!["id"] as! String
   self.friends.append(id)
   // call fetchFriendMarkers when you receive the friend data
   self.fetchFriendsMarkers(id)
 })
 query?.observe(.childRemoved, with: { (snapshot) in
   let friend = snapshot.value as? NSDictionary
   let id = friend!["id"] as! String
   var index: Int
   for i in self.friends{
      if i == id{
         index = self.friends.index(of: i)!
         self.friends.remove(at: index)
      }
   }
 })
}

private func fetchFriendsMarkers(friend: String){
  let query1 = ref?.child("user-locations").child(friend)
     query1?.observe(.childAdded, with: { (snapshot) in

  })
  query1?.observe(.childChanged, with: { (snapshot) in

  })
  query1?.observe(.childRemoved, with: { (snapshot) in  
  })

}

...
fetchFriends()