我希望通过segue将一个包含用户信息的数组从一个控制器拉到另一个控制器。当一切都在tableview中时,我能够做到这一点,但当它在常规的controller视图中时,我不能做到这一点。有人能帮忙吗?
视图控制器
var userArray = [User]()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showGuestView" {
let guestVC = segue.destination as! GuestUserViewController
guestVC.ref = userArray.ref //this would work using userArray[indexPath.row].ref if it was a tableview
//ref represents DatabaseReference?
}
}
DatabaseClass.fetchUser() { (user) in
if let user = user {
self.userArray.append(user)
}
数据库类
func fetchUser(completion: @escaping (User?)->()){
let currentUser = Auth.auth().currentUser!
let postRef = Database.database().reference().child("getinfo").child(currentUser.uid)
postRef.observe(.value, with: { (snapshot) in
for childSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
let request = childSnapshot.key
let userRef = self.databaseRef.child("users").child(request)
userRef.observeSingleEvent(of: .value, with: { (currentUser) in
let user: User = User(snapshot: currentUser)
completion(user)
})
}
})
}
用户结构
struct User {
var firstname: String!
var uid: String!
var ref: DatabaseReference!
init(firstname: String, uid: String){
self.firstname = firstname
self.uid = uid
self.ref = Database.database().reference()
}
init(snapshot: DataSnapshot){
if let snap = snapshot.value as? [String:Any] {
self.firstname = snap["firstname"] as! String
self.uid = snap["uid"] as! String
}
self.ref = snapshot.ref
}
func toAnyObject() -> [String: Any]{
return ["firstname":self.firstname, "uid":self.uid]
}
}
最佳答案
我可以看到userArray
是一个用户数组,因此不能使用userArray.ref
,因为数组的定义中没有任何类似于ref
的属性。在table视图中,它之所以工作是因为您拉了一个user
对象,然后传递了ref
。
在传递给来宾视图控制器之前,尝试获取选定的用户实例。
let user = userArray[selected user index];
guestVC.ref = user.ref