0

Blockquote

I am trying to load the details from Firebase in table view controller. Following is the service invocation and the promise is getting fulfilled even before the observation of all events are completed.

import Firebase
import PromiseKit

class ContactsTableViewModal: NSObject {
    var contacts: [User] = []
    func getContacts() ->Promise<[User]> {
        return Promise {
            seal in
            Database.database().reference().child("users").observe(.childAdded, with: { [unowned self] (snapShot) in
                guard let contactsDict = snapShot.value as? [String: AnyObject]
                    else {
                        return seal.reject(UserError.inputValuesAreEmpty)
                }
                ///Observe the user one at a time from realtime database
                let user = User(userName: (contactsDict["username"] as! String), userEmail: contactsDict["email"] as! String)
                self.contacts.append(user)
                seal.fulfill(self.contacts)
            }) { (error) in
                seal.reject(error)
            }

        }
    }
}

///The following is calling method invoked from my tableview controller.
func fetchContacts() {
        self.contactsTableViewModal.getContacts().done { [unowned self] (users) in
            *//Promise is fulfilling immediately and returning nil users*
            self.contactsTableView.contacts = users
            DispatchQueue.main.async {
                self.contactsTableView.reloadData()
            }
        }.catch { (error) in
            print(error)
        }
    }
Ajay
  • 41
  • 1
  • 7
  • does the child("users") really exists in top level of firebase tree? – BharathRao Nov 14 '19 at 05:41
  • I think it's because you are observing a single child and once it is delivered, `promise` is fulfilled. You need to use a different api to fetch all the users/contacts then fulfill the `promise`. – Kamran Nov 14 '19 at 05:50

0 Answers0