AlexVilla147
AlexVilla147

Reputation: 283

Firebase .childAdded does not work, because observed child might not exist yet

I want to use some data out of the Database for later purpose. However the data I want to load might not exist yet, because the observed data is a dictionary of friend requests which do not exist at the very first time the app is used. Although the .childAdded observer should do it, it just stops there and the code is not executed further

func getFriendRequest(_ uid: String, completion: @escaping ([String]) -> Void) {
    var friendRequests = [String]()
    let currentUserRef = DatabaseReference.users(uid: self.currentUser.uid).reference()
    currentUserRef.child("sendFriendRequest").observe(.childAdded, with: { (snap) in
        let request = FriendRequest(dictionary: snap.value as! [String : Any])
        let requestedUid = request.uid
        print(requestedUid)
        friendRequests = [requestedUid]
        completion(friendRequests)
    }, withCancel: nil)
}

It does not get into the observe method ... Has anyone an idea why that is?

Upvotes: 0

Views: 404

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

The .childAdded completion handler will only be called when there is a child. If there are no child nodes it will not be invoked until you add a child under sendFriendRequest.

Upvotes: 1

Related Questions