传递Firebase数据库参考数据

时间:2018-07-11 06:05:27

标签: swift firebase firebase-realtime-database

我正在寻找一个数组,该数组包含使用segue从Firebase从一个控制器拉到另一个控制器的用户信息。当所有内容都在表视图中时,我可以执行此操作,但是在常规控制器视图中时,则不能执行此操作。有人可以帮忙吗?

视图控制器

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]
    }
}

1 个答案:

答案 0 :(得分:1)

我可以看到userArray是一个用户数组,因此您不能使用userArray.ref,因为该数组在定义中没有像ref这样的属性。在表视图中,它之所以起作用是因为您拉了user对象然后传递了ref

在传递给访客视图控制器之前尝试获取选定的用户实例。

let user =  userArray[selected user index];
guestVC.ref = user.ref