Как добавить блок завершения в запрос .childAdded firebase? - PullRequest
1 голос
/ 09 апреля 2019

У меня есть функция выборки ниже.Как добавить блок завершения, чтобы после его завершения я мог что-то сделать?

Этот запрос будет запускать код внутри более одного раза.

func getFollowers() {
    print("get followers called")
    let ref = Database.database().reference()
    ref.child("users2").child((Auth.auth().currentUser?.uid)!).child("Following").observe(.childAdded) { (snap) in
        let personBeignFollow = snap.key
        self.peopleUserFollows.append(personBeignFollow)
        print("Appened: ", personBeignFollow)
        self.fetchAllUserFirstPostMedia(user: personBeignFollow)
    }
}

Я посмотрел здесь , но не смог заставить его работать.

Вот что я попробовал:

    func getFollowers(_: ()-> ()) {
    print("get followers called")
    let ref = Database.database().reference()
    ref.child("users2").child((Auth.auth().currentUser?.uid)!).child("Following").observe(.childAdded) { (snap) in
        let personBeignFollow = snap.key
        self.peopleUserFollows.append(personBeignFollow)
        print("Appened: ", personBeignFollow)
        self.fetchAllUserFirstPostMedia(user: personBeignFollow)
    }
}

Тогдагде это называется:

getFollowers() {
   self.collectionView.reloadData()
}

1 Ответ

0 голосов
/ 09 апреля 2019

В объявлении функции вы можете добавить следующее:

func getFollowers(_ completion: @escaping () -> Void) {
    print("get followers called")
    let ref = Database.database().reference()
    ref.child("users2").child((Auth.auth().currentUser?.uid)!).child("Following").observe(.childAdded) { (snap) in
        let personBeignFollow = snap.key
        self.peopleUserFollows.append(personBeignFollow)
        print("Appened: ", personBeignFollow)
        self.fetchAllUserFirstPostMedia(user: personBeignFollow)

       // tell the calling function to execute the completion handler again
       completion()
    }
}

тогда, чтобы использовать его, вы должны сделать что-то вроде этого:

getFollowers {
 // whatever you want to do after the query has run
}

Это не имеет прямого значения, но как обычная практика проектирования, было бы неплохо передать ваши новые данные, полученные из запроса, в качестве параметра в обработчике завершения, а не присваивать свойство классу.

Это будет выглядеть примерно так:

func getFollowers(_ completion: (String) -> Void) {
    ref.child("users2").child((Auth.auth().currentUser?.uid)!).child("Following").observe(.childAdded) { (snap) in
        let personBeignFollow = snap.key
        print("Appened: ", personBeignFollow)        
       // tell the calling function to execute the completion handler again
       completion(personBeignFollow)
    }
}

и тогда ваш вызывающий сайт может выглядеть так:

getFollowers { newUser in
    self.fetchAllUserFirstPostMedia(user: newUser)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...