2016-09-20 55 views
0

我有一些代碼獲取每個帖子並在uitableviewcontroller中顯示它。即讓所有的火力職位的代碼是這樣的:只顯示來自當前用戶的信息 - firebase swift

viewDidLoad { 
dbRef = FIRDatabase.database().reference().child("feed-items") 
    startObersvingDB() 

} 

func startObersvingDB() { 
    dbRef.observeEventType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in 
     var newUpdates = [Sweet]() 

     for update in snapshot.children { 
      let updateObject = Sweet(snapshot: update as! FIRDataSnapshot) 
      newUpdates.append(updateObject) 

     } 

     self.updates = newUpdates 
     self.tableView.reloadData() 


    }) { (error: NSError) in 
     print(error.description) 
    } 
} 

我怎樣才能修改部分從一個特定的用戶名只得到更新? 我在火力結構是這樣的:

feed-items { 
    unique-user-id { 
      post: "This is a post" 
      byUsername: "MyUser" 
    } 
} 

那麼代碼應該做的,是取了byUsername串 - 我只是無法弄清楚如何更新我的代碼來做到這一點。希望你們能幫助我:-)

回答

3

試試這個: -

斯威夫特3

func startObersvingDB() { 
FIRDatabase.database().reference().child("feed-items").queryOrdered(byChild: "byUsername").queryEqual(toValue: "MyUser").observe(.value, with: { (snapshot: FIRDataSnapshot) in 
    var newUpdates = [Sweet]() 

    for update in snapshot.children { 
     let updateObject = Sweet(snapshot: update as! FIRDataSnapshot) 
     newUpdates.append(updateObject) 

     } 

     self.updates = newUpdates 
     self.tableView.reloadData() 


     }) { (err) in 
     print(err!.localisedDescription)  
     } 
    } 

斯威夫特2

func startObersvingDB() { 
FIRDatabase.database().reference().child("feed-items").queryOrderedbyChild("byUsername").queryEqualtoValue("MyUser").observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in 
    var newUpdates = [Sweet]() 

    for update in snapshot.children { 
     let updateObject = Sweet(snapshot: update as! FIRDataSnapshot) 
     newUpdates.append(updateObject) 

    } 

    self.updates = newUpdates 
    self.tableView.reloadData() 


    }) { (error: NSError) in 
     print(error.description) 
    } 
    } 
0

從我可以收集你取feed-items的每個孩子與for update in snapshot.children {...}你永遠不會使用密鑰unique-user-id實際獲取特定的用戶ID。你必須要麼寫database rule以允許用戶只能查看自己的物品或者你可以用下面的方法(SWIFT 3語法):

1)從FIRAuth獲取用戶ID:

if let user = FIRAuth.auth()?.currentUser { 
    for profile in user.providerData { 
     providerDataID = profile.providerID // save UID in variable e.g. providerDataID 
     // fetch other FIRAuth stuff 
    } 

2 )僅獲得飼料項與UID:

ref.child("feed-items").child(providerDataID).observeSingleEvent(of: .value, with: { (snapshot) in  
    if let userInfoDict = snapshot.value as? NSDictionary { 
    // get values from the proper providerDataID ONLY 
} 

備選: 做在你的代碼檢查每個孩子的UID for循環的時候,如果它是你的用戶匹配,但會佔用一些帶寬,如果你有一個大的數據庫

+0

唯一的用戶ID被「跳過」,因爲我只尋找snapshot.children - 但有人已經找到我的答案:-)儘管感謝您的時間! –

相關問題