Code only retrieving one value from data in Firebase

后端 未结 2 1647
情歌与酒
情歌与酒 2021-01-24 15:31

As the title suggests, I\'m trying to retrieve some data from firebase database, but my code\'s not working. I have three children (I guess that\'s how you call them) inside \"P

相关标签:
2条回答
  • 2021-01-24 16:04
    import UIKit
    import FirebaseDatabase
    
    class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
        // MARK: - variables
        var postDB: DatabaseReference!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // getting a node from database //
            postDB = Database.database().reference().child("Posts")
    
            // observing data changes //
            postDB.observe(DataEventType.value) { (dataSnapshot) in
                self.postArray.removeAll()
                if dataSnapshot.childrenCount > 0 {
                    for post in dataSnapshot.children.allObjects as! [DataSnapshot] {
                        let object = post.value as! [String: Any]
                        let description = object["description"] as! String
                        let title = object["title"] as! String
                        let userName = object["username"] as! String
                        let model = postStruct(title: title, description: description, username: userName))
                        self.postArray.append(model)
                    }
                }
                self.tableView.reloadData()
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-24 16:14

    Try this – the code replaces what you currently have in the snapshot handler.

    if let firebaseList = snapshot.children.allObjects as? [FIRDataSnapshot] {
            if let swiftList = snapshot.value as? [String:AnyObject] {
                for firebaseItem in firebaseList {
                    let childID = firebaseItem.key as String
                    let swiftItem = swiftList[childID]
                    let postTitle = swiftItem?["title"] as? String
                    let postUsername = swiftItem?["username"] as? String
                    let postDesc = swiftItem?["description"] as? String
                    let postArray = postStruct(title: postTitle, description: postDesc, username: postUsername)
                    self.newPost.insert(postArray, at: 0)
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题