ios - 在 tableViewCell 上显示来自子节点的所有数据

标签 ios swift firebase uitableview firebase-realtime-database

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

我的 firebase JSON 结构的一个片段是:

 "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",
    },

表格 View 单元格(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"))
    }
}

编辑: View Controller (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
  }
}

现在代码运行,关注者的个人资料图片和全名打印在控制台上,但不会在应用程序的表格 View 中显示任何内容 - 提前致谢:)

更新: 用户模型定义

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

最佳答案

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

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

根据要求,这里有一种快速(但很脏)的方法来创建用户对象并刷新 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()

关于ios - 在 tableViewCell 上显示来自子节点的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55262362/

相关文章:

ios - 当转到另一个 ViewController 时,TabBar 嵌入式 NavigationController 栏消失

swift - Firebase 使用用户 ID 检索 user.email

objective-c - 删除 Omniture 实例的 pageName 变量

ios - swift : I am getting error in firebase mobile authentication

ios - UndoManager 和多个 MOC

javascript - 无法从 firebase 获取 token 用于消息传递

android - 找不到与包名称匹配的客户端 (Google Analytics) - 多个 productFlavors/application id

iphone - 显示 UIImagePickerController 后 UITextfields 空白

xcode - 快速生成节点无限

ios - 将 NSNotification.userInfo[UIKeyboardAnimationCurveUserInfoKey] 转换为枚举