2017-09-20 151 views
0

我有一个tableView,当前是我的数据库中所有用户的列表,使用下面的fetchAllUsers函数。如何从每个用户提取个人用户ID并将其传递到另一个函数?所以如果我点击表中的第一个用户,我可以将该用户的特定用户ID传递给另一个函数?从firebase数组中检索数据

func fetchAllUsers(completion: @escaping ([User])->()) { 

    let userRef = self.databaseRef.child("users") 
    userRef.observe(.value, with: { (userdata) in 

     var resultsArray = [User]() 
     for user in userdata.children { 

      let user = User(snapshot: user as! DataSnapshot) 
      resultsArray.append(user) 

     } 

     completion(resultsArray) 

    }) { (error) in 
     print(error.localizedDescription) 
    } 

} 
+1

请显示你的'User' – 3stud1ant3

回答

1

首先,为方便起见,下面介绍一些可以添加到User类的方法。

static var ref: DatabaseReference { 
    return Database.database().reference(withPath: "users") 
} 

var ref: DatabaseReference { 
    return User.ref.child(snapshot.key) 
} 

以及针对DataSnapshot的扩展,使它们映射到User容易。

extension DataSnapshot { 
    var childrenSnapshots: [DataSnapshot] { 
     return children.allObjects as? [DataSnapshot] ?? [] 
    } 
} 

最后,我们可以重构您的fetchAllUsers函数以利用帮助器。

func fetchAllUsers(completion: @escaping ([User]) ->()) { 
    User.ref.observe(.value, with: { (snapshot) in 
     completion(snapshot.childrenSnapshots.map { User(snapshot: $0) }) 
    }) { (error) in 
     print(error.localizedDescription) 
    } 
} 

现在一切都比较容易阅读,让我们考虑你的目标 - 你想从表视图中检索选定用户的ID。用户的ID本质上是用户快照的关键,我们用它来实例化User类。

您的User.init函数应该使用快照来填充类属性,因此您也可以使用此机会检索快照的关键字并在User类上设置一个属性来存储它。有一个更好的方法。

// MARK: Properties 

var snapshot: DataSnapshot? 
var key: String? { 
    return snapshot?.key 
} 

... 

// MARK: Lifecycle 

init(snapshot: DataSnapshot) { 

    self.snapshot = snapshot 

    ... 
} 

当你初始化一个User与快照,您可以存储快照后,并使用一个计算属性检索的关键。因此,只要您将用户存储在数组中,就可以使用所选单元格的indexPath在数组中找到所选用户。

var users: [Users]? 

... 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    if users?.indices.contains(indexPath.row) == true { 
     performSegue(withIdentifier: "showUser", sender: users?[indexPath.row]) 
    } 
} 

... 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

    switch (segue.destination, sender) { 
    case (let controller as ViewController, let user as User): 
     controller.user = space 
    default: 
     break 
    } 
} 

一旦你有你的用户,你有你的钥匙。选择一个单元格后,您需要执行segue - 我喜欢使用sender参数来传递与segue相关的任何内容。例如,您可以传递所选的User对象并将其设置在目标控制器中。

0

如果我假设您的模型User具有userId,并且您已经提到要获取resultsArray中的所有用户数据并将其填充到tableView中。

现在选择任何一行tableView,你可以通过实现UITableView的didSelectRowAt委托来得到你的个人用户数据。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let individualUser : User = resultsArray[indexPath.row] 
    self.anotherFunc(individualUser.userId) 
}