在Collection View Swift 4和Firebase中显示好友请求列表

时间:2018-07-31 00:30:49

标签: swift firebase firebase-realtime-database

我有一个很简单的问题。我想在集合视图中显示用户的好友请求列表。我已经实现了该功能,可以帮助我发送好友请求,该请求在Firebase数据库中效果很好,我所需要的只是正确显示列表。这是我用来执行该操作的代码段。

@objc func FriendUnFriendSelf(){

    guard let currentLoggedInUser = Auth.auth().currentUser?.uid else {return}

    guard let userId = user?.uid else {return}

    if addOrSelfButton.titleLabel?.text == "Added"{

        //unadd user

        Database.database().reference().child("friendship").child(currentLoggedInUser).child(userId).removeValue (completionBlock: {(err, ref) in
            if let err = err{
                print("Failed to delete user request:", err)
                return
            }
            print("Successfully delete user request:", self.user?.username ?? "")

            self.addOrSelfButton.setTitle("Add", for: .normal)
            self.addOrSelfButton.setTitleColor(UIColor.rgb(red: 32, green: 234, blue: 255), for: .normal)
        })
    }else{

        let fromID = currentLoggedInUser
        let toID = userId

        // "0": wait for partner's acceptance
        // "1": receive a new request, the user can choose to accept or reject
        // "2": establish the friendship

        let senderFriendRef = Database.database().reference().child("friendship").child(fromID)
        senderFriendRef.updateChildValues([toID : 0])
        let receiverFriendRef = Database.database().reference().child("friendship").child(toID)
        receiverFriendRef.updateChildValues([fromID: 1])

    }
}

但是当我想显示朋友列表时,我得到的任何回报都没有,这是显示列表的代码。

func fetchRequest() {

    if let myID = Auth.auth().currentUser?.uid{

        let ref = Database.database().reference().child("friendship").child(myID)

        ref.observe(.childAdded, with: { (snapshot) in

            if (snapshot.value as! Int == 1) {

                let requestID = snapshot.key

                let userRef = Database.database().reference().child("users").child(requestID)

                userRef.observeSingleEvent(of: .value, with: { (snapshot) in

                    guard let dictionaries = snapshot.value as? [String: Any] else {return}



                    dictionaries.forEach({ (key, value) in

                        guard let userDictionary = value as? [String: Any] else {return}

                        var user = User(uid: key, dictionary: userDictionary)

                        user.id = requestID

                        self.friendRequest.append(user)

                        self.collectionView?.reloadData()

                    })

                },withCancel: nil)}

        }, withCancel: nil)

    }

}

有关如何执行此操作的任何建议?非常感谢。

0 个答案:

没有答案