2016-09-20 80 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 - 但有人已经找到我的答案:-)尽管感谢您的时间! –