如何在Firebase中循环播放AutoIdChild?

时间:2017-01-24 22:31:38

标签: ios firebase swift3 firebase-realtime-database

我有像Twitter这样的社交应用程序,当用户查找另一个用户时,我想看看登录用户是否跟随其他用户,但我不知道如何循环查看是否登录用户已经跟随另一个。

{
  "follower" : {
    "mt0fzirhMhazIcy90MRWuRpTfmE2" : {
      "-KbHXdeiOfGXzvavuQ_5" : {
        "uid" : "dEXaVLDOSPfJa3zTyUNqAEtVuMR2"
      }
    }
  },
  "following" : {
    "dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
      "-KbHXdehbkeMvDyzNpRE" : {
        "uid" : "mt0fzirhMhazIcy90MRWuRpTfmE2"
      }
    }
  },
  "handles" : {
    "jcadmin" : "mt0fzirhMhazIcy90MRWuRpTfmE2",
    "jcbest" : "dEXaVLDOSPfJa3zTyUNqAEtVuMR2"
  },
  "user_profiles" : {
    "dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
      "about" : "Hello world",
      "handle" : "jcbest",
      "name" : "Juan Carlos Estevez Rodriguez",
      "profile_pic" : "https://firebasestorage.googleapis.com/v0/b..."
    },
    "mt0fzirhMhazIcy90MRWuRpTfmE2" : {
      "about" : "Hello",
      "handle" : "jcadmin",
      "name" : "Juan Carlos",
      "profile_pic" : "https://firebasestorage.googleapis.com/v0..."
    }
  }
}

这是我的数据库,我想要的是这样的

   self.databaseRef.child("following").child((self.loggedInUser?.uid)!).observe(.value, with: { (snapshot) in
        let snapshot = snapshot.value as? [String: AnyObject]

        if("The other user UID exists in the following")
        {
            self.followButton.tittleLabel = "Unfollow"
        }

    })

2 个答案:

答案 0 :(得分:1)

您不需要$autoId,只需使用关注者/关注用户的$uid作为关键字。

"follower" : {
  "mt0fzirhMhazIcy90MRWuRpTfmE2" : {
    "dEXaVLDOSPfJa3zTyUNqAEtVuMR2": true
  }
},
"following" : {
  "dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
    "mt0fzirhMhazIcy90MRWuRpTfmE2": true
  }
},

然后你可以观察/ after / $ uid / $ userId的值,切换快照值以确定它是Bool等于true还是仅null

let uid = FIRAuth.auth()!.currentUser!.uid
let ref = FIRDatabase.database().reference(
    withPath: "following/\(uid)/$userId"
)

ref.observe(.value, with: { (snapshot) in
    switch snapshot.value {
    case let value as Bool where value:
        // value was a Bool and equal to true
        self.followButton.tittleLabel = "Unfollow"
    default:
        // value was either null, false or could not be cast
        self.followButton.tittleLabel = "Follow"
    }
})

答案 1 :(得分:1)

使用Firebase的push() / childByAutoId()方法非常适合获取保证拥有独特子元素的集合,并且按时间顺序排序,有点像大多数其他语言中的数组。

但是您的用户集合属于不同类型:它更像是一个集合。在一个集合中,每个值只能出现一次。在Firebase数据库中,您可以为这样的集合建模:

{
  "follower" : {
    "mt0fzirhMhazIcy90MRWuRpTfmE2" : {
        "dEXaVLDOSPfJa3zTyUNqAEtVuMR2": true
    }
  },
  "following" : {
    "dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
        "mt0fzirhMhazIcy90MRWuRpTfmE2": true
    }
  },
  ...

因此,这会将UID作为键,保证每个关注者只能在集合中出现一次(因为键在其上下文中必须是唯一的)。值true就在那里,因为数据库无法存储没有值的键,它没有意义。

现在您可以通过以下方式访问用户“关注”:

self.databaseRef
    .child("following")
    .child((self.loggedInUser?.uid)!)
    .observe(.value, with: { (snapshot) in
        for child in snapshot.children {
            print("Following \((child.key!))"
        }
    })