【问题标题】:Display all data from child node on a tableViewCell在 tableViewCell 上显示来自子节点的所有数据
【发布时间】:2019-08-11 05:47:34
【问题描述】:

我无法在表格视图单元格中显示用户的所有关注者及其个人资料图片和全名(类似于 instagram)。

我的 firebase JSON 结构的 sn-p 是:

 "followers" : {
    "FoFQDAGGX9hntBiBdXYCBHd8yas2" : {
      "CjeP35ceAQZJuUPhm7U1eF3Yq4F3" : true,
      "FjS4wUpXAUa5aWwXkjvujHxE4He2" : true,
      "Gmg1ojNoBiedFPRNSL4sBZz2gSx2" : true,
      "PqMkClaPM3W8k7ZSgzAHb3yne5D3" : true,
      "buS4recuDpdg60ckFqwjoU344TC2" : true
    },
 "users" : {
    "CjeP35ceAQZJuUPhm7U1eF3Yq4F3" : {
      "email" : "bbbb@gmail.com",
      "fullname" : "Bbbb",
      "profileImageUrl" : "https://firebasestorage.googleapis.com/v0/b/pinion-4896b.appspot.com/o/profile_image%2FCjeP35ceAQZJuUPhm7U1eF3Yq4F3?alt=media&token=0449c633-b397-4452-b2df-41f3a5390084",
      "work" : "Nottingham",
    },

表格视图单元格(FollowersTableViewCell)中的代码:

@IBOutlet weak var followersProfileImage: UIImageView!
@IBOutlet weak var followersNameLabel: UILabel!

var user: UserModel? {
    didSet {
        updateView()
    }
}
func updateView() {
    followersNameLabel.text = user?.fullname
    if let photoUrlString = user?.profileImageUrl {
        let photoUrl = URL(string: photoUrlString)
        followersProfileImage.sd_setImage(with: photoUrl, placeholderImage: UIImage(named: "placeholderImg"))
    }
}

编辑: 视图控制器(FollowersViewController)中的代码

@IBOutlet weak var tableView: UITableView!

var users: [UserModel] = []

func loadusers() {
    let ref = Database.database().reference()
    guard let currentUser = Auth.auth().currentUser?.uid else { return }

    var followersNames = [String]()
    var profileImage = [String]()

    let followersRef = ref.child("followers").child(currentUser) //retreives all nodes in the following node
    followersRef.observe(DataEventType.value, with: { snapshot in
        print(snapshot.children.allObjects)
        for child in snapshot.children { //build the array of keys
            let snap = child as! DataSnapshot
            let key = snap.key

            let userRef = ref.child("users").child(key) //get the user name and profile image from the users node
            userRef.observeSingleEvent(of: .value, with: { snapshot in
                let followersName = snapshot.childSnapshot(forPath: "fullname").value as! String
                let followersProfileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String
                print(followersName)
                print(followersProfileImageUrl)

                followersNames.append(followersName)
                profileImage.append(followersProfileImageUrl)
                self.tableView.reloadData()
            })
        }
    })
}
extension FollowersViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FollowersTableViewCell", for: indexPath) as! FollowersTableViewCell
    let user = users[indexPath.row]
    cell.user = user
    return cell
  }
}

现在代码运行,关注者的头像和全名打印在控制台上,但在应用程序的表格视图上没有显示任何内容 - 在此先感谢 :)

更新: 用户模型定义

class UserModel {
    var email: String?
    var work: String?
    var profileImageUrl: String?
    var fullname: String?
    var id: String?
}
extension UserModel {
    static func transformUser(dict: [String: Any], key: String) -> UserModel {
        let user = UserModel()
        user.email = dict["email"] as? String
        user.work = dict["work"] as? String
        user.profileImageUrl = dict["profileImageUrl"] as? String
        user.fullname = dict["fullname"] as? String
        user.id = key
        return user
    }
}

【问题讨论】:

    标签: ios swift firebase uitableview firebase-realtime-database


    【解决方案1】:

    您的 TableView 不显示任何数据,因为您在任何时候都没有填充 users 数组。

    我可能想在observeSingleEvent 实现中实例化一个UserModel 对象,将该对象添加到users 数组并在此之后调用reloadData(或insertRows)方法。 (而不是在实现块之外)

    根据要求,这是一种创建用户对象和刷新 UI 的快速(但很脏)的方法

    let user = UserModel()
    user.fullname = snapshot.childSnapshot(forPath: "fullname").value as? String
    user.profileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as? String
    
    self.users.append(user)
    self.tableView.reloadData()
    

    【讨论】:

    • 感谢您的回复!我收到一条错误消息,提示“无法将'String'类型的值转换为预期的参数类型'UserModel'”,因此我为关注者姓名和个人资料图像创建了2个数组 - 现在名称打印在控制台中,但不在应用程序上。我已将编辑添加到上面的代码中
    • 你要创建一个UserModel类的实例,你能附上类定义吗?
    • 您的代码仍然知道显示 UserModel 对象,填充 followerNames 和 profileImage 没有任何好处
    • 哦,我明白了,谢谢,我已经附加了 UserModel 类 - 我对此很陌生,所以感谢您的帮助
    • 创建一个新模型而不是使用 UserModel 会更好吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多