2017-01-24 101 views
0

我有這樣的社交應用程序像twitter和當用戶尋找另一個用戶我想看看登錄的用戶是否跟隨其他用戶,但我不知道如何循環,並找出已登錄的用戶是否已經跟隨另一個。如何循環訪問Firebase中的AutoIdChilds?

{ 
    "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" 
     } 

    }) 

回答

1

你並不需要一個$autoId,你可以只使用跟隨/以下用戶的$uid的關鍵。

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

然後你可以觀察/下/ $ UID/$用戶id,切換快照值的值,以確定它是否是一個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

使用火力地堡的push()/childByAutoId()方法是偉大的得到一個集合,它保證具有獨特的兒童,即按時間順序排列,有點像在大多數其他語言的數組。

但是你的用戶集合是不同類型的:它更像一個集合。在一組中,每個值只能出現一次。在火力地堡數據庫你會模擬一組這樣的:

{ 
    "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!))" 
     } 
    })