Firebase updateChildValue在一种情况下有效,但在另一种情况下无效

时间:2019-07-19 17:18:10

标签: ios swift firebase firebase-realtime-database

我正在尝试重新创建instagram Follow和取消关注功能。当按下跟随按钮时,我在user.swift文件中调用跟随功能。用户跟随者结构完美运行,但用户跟随数据库调用似乎无效。两者都有相同的逻辑,只是声明相反。听起来可能有些含糊,但代码不言自明。

user-folowers结构可以很好地工作,但是在firebase上似乎无法创建用户关注的结构。

class User{
    var username: String!
    var name: String!
    var profileImageUrl: String!
    var uid: String!
    var isFollowed = false

    init(uid: String, dictionary: Dictionary<String, AnyObject>){
        self.uid = uid
        if let username = dictionary["username"] as? String {
            self.username = username
        }
        if let name = dictionary["name"] as? String {
            self.name = name
        }
        if let profileImageUrl = dictionary["profileImageUrl"] as? 
String {
            self.profileImageUrl = profileImageUrl
        }
    }

    func follow(){
        guard let currentUid = Auth.auth().currentUser?.uid else { 
return }

        // set is followed to true
        self.isFollowed = true

        // add followed user to current user-following structure
        Database.database().reference().child("user- 
following").child(currentUid).updateChildValues([self.uid: 1])

        // add current user to followed user-follower structure
        Database.database().reference().child("user- 
followers").child(self.uid).updateChildValues([currentUid: 1])

    }

    func unfollow(){
        guard let currentUid = Auth.auth().currentUser?.uid else { 
return }

        // set is followed to false
        self.isFollowed = false

        // remove user from current user-following structure
        Database.database().reference().child("user- 
following").child(currentUid).child(self.uid).removeValue()

        // remove current user from user-follower structure
        Database.database().reference().child("user- 
followers").child(self.uid).child(currentUid).removeValue()

    }
    )

0 个答案:

没有答案