如何从数据库中提取用户并使用Firebase将其列在表格视图中? [英] How to pull users from database and list them in a table view using firebase?

查看:85
本文介绍了如何从数据库中提取用户并使用Firebase将其列在表格视图中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase制作iOS应用我想检索我的数据库中的所有用户,并在表格视图中显示他们的名字和个人资料图片。这是我的 TableViewCell 的代码:
$ b

  import UIKit 
导入FirebaseDatabase
导入FirebaseAuth
导入SDWebImage

类HomeTableViewCell:UITableViewCell {

$ b @IBOutlet弱var nameLabel:UILabel!
@IBOutlet弱var profileImageView:UIImageView!
@IBOutlet弱var likeImageView:UIImageView!
@IBOutlet弱var messageImageView:UIImageView!
@IBOutlet弱var likeCountButton:UIButton!

var homeVC:HomeViewController?
var postReference:DatabaseReference!
$ b $ var post:UserFile?{
didSet {
updateView()
}
}

var user:UserFile? {
didSet {
updateUserInfo()
}
}

覆盖func awakeFromNib(){
super.awakeFromNib()

nameLabel.text =

let berryTapGesture = UITapGestureRecognizer(target:self,action:#selector(handleLikeTap))

likeImageView.addGestureRecognizer(berryTapGesture)
likeImageView.isUserInteractionEnabled = true


重写func setSelected(_ selected:Bool,animated:Bool){
super.setSelected(selected,动画:动画)
}

func updateView(){
如果让photoURL = post?.picURL {
profileImageView.sd_setImage(with:URL(string:photoURL ))
}

API.Post.REF_POSTS.child(post!.id!)。observeSingleEvent(of:.value,with:{postSnapshot in
if let postDictionary = postSnapshot.value as?[String:Any] {
let post = UserFile.transformPost(postDictionary:postDictionary,key:postSnapshot.key)
self.updateLike(post:post)
}
})
API.Post.REF_POSTS.child观察(.childChanged,用:{$快照$ b $如果让value = snapshot.value as? Int {
self.likeCountButton.setTitle(\(value)berries,for:.normal)
}
})
}

func updateLike(post:UserFile){
let imageName = post.berries == nil || !post.isBerried! ? berry:berrySelected
likeImageView.image = UIImage(名字:imageName)

//显示莓果消息
guard let count = post.berryCount else {
返回
}

if count!= 0 {
likeCountButton.setTitle(\(count)berries,for:.normal)
}否则,如果post.berryCount == 0 {
likeCountButton.setTitle(成为第一个喜欢这个,为:.normal)
}
}

func如果var post = currentData.value as?[String:AnyObject],let uid = Auth($ {$ b $ ref.runTransactionBlock({(currentData:MutableData) - > TransactionResult in
) .auth()。currentUser?.uid {
var berries:Dictionary< String,Bool>
berries = post [berries] as?[String:Bool] [:]
var likeCount = post [berryCount] as?Int ?? 0
如果让_ =浆果[uid] {
//不同于帖子并从星星中删除自己
likeCount - = 1
berries.removeValue(forKey:uid)
}其他{
//喜欢这个帖子,并加上自己星星
likeCount + = 1
berries [uid] = true
}
post [berryCount] = likeCount为AnyObject?
发布[浆果] =浆果作为AnyObject?
$ b $ currentData.value = post
$ b $返回TransactionResult.success(withValue:currentData)
}
返回TransactionResult.success(withValue:currentData)$ b如果让error = error {
print(error.localizedDescription)
}

如果让postDictionary =
$ b $)快照?.value as? (String:Any){
let post = UserFile.transformPost(postDictionary:postDictionary,key:snapshot!.key)
self.updateLike(post:post)
}
}


func handleLikeTap(){
postReference = API.Post.REF_POSTS.child(post!.id!)
incrementberries(forReference:postReference)


重写func prepareForReuse(){
super.prepareForReuse()
profileImageView.image = UIImage(命名为:industribune-default-no-profile-pic)


func updateUserInfo(){
nameLabel.text = user?.username
如果让photoURL = user?.profileImageURL {
profileImageView.sd_setImage (带有:URL(字符串:photoURL),placeholderImage:UIImage(命名为:industribune-default-no-profile-pic))
}
}


}

我在 HomeViewController

 导入UIKit 
导入FirebaseAuth
导入FirebaseDatabase
导入FirebaseStorage
导入Firebase

类HomeViewController:UIViewController {


@IBOutlet weak var tableView:UITableView!
@IBOutlet weak var activityIndi​​catorView:UIActivityIndi​​catorView!
$ b var post = [UserFile]()
var users = [UserFile]()

重写func viewDidLoad(){
super.viewDidLoad )
//用于性能设置估计的行高
tableView.estimatedRowHeight = 1
//同时也请求使用AutoLayout动态调整内容
tableView.rowHeight = UITableViewAutomaticDimension

//tableView.delegate = self
tableView.dataSource = self
$ b loadPosts()
}

覆盖func didReceiveMemoryWarning ){
super.didReceiveMemoryWarning()
//处理任何可以重新创建的资源。

$ b $ func loadPosts(){
activityIndi​​catorView.startAnimating()

API.User.observePosts {(newPost)in
guard let userID = newPost.uid else {return}
self.fetchUser(uid:userID,completed:{
//在用户
//被缓存后追加新的Post和Reload
self.posts.append(newPost)
self.activityIndi​​catorView.stopAnimating()
self.tableView.reloadData()
})
}
}

func fetchUser(uid:String,completed:@escaping() - > Void){

API.User.observeUser(withID:uid){$ in
self.users.append(用户)

完成()
}
}


}

扩展HomeViewController:UITableViewDataSource {

func tableView(_ tableView:UITableView,numberOfRowsInSection部分:Int) - > Int {
return posts.count
}

func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath) - > UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:HomeTableViewCell,for:indexPath)as! HomeTableViewCell

cell.post = posts [indexPath.row]
cell.user = users [indexPath.row]
cell.homeVC = self

返回单元格
}

}

我有很多在我的项目中发生的疯狂如此请告诉我,如果您有任何问题和我做错了什么。如果这太复杂了,我已经准备好抹去一切,重新开始。



我真的认为我遵循所有的指导原则来提出一个问题不喜欢关闭这个问题或者其他东西。

解决方案

这是很多代码。试试这个超级简化的例子。为此,用户节点仅将名称存储为子节点,但也可以具有图像,电子邮件地址等。



示例用户节点

 用户
uid_0:
名称:Bert
uid_1:
名称:Ernie

和一些代码

  var usersArray = [[String:Any]]()//一个字典数组。 
$ b $ class ViewController:UIViewController {
//在这里设置firebase引用
覆盖func viewDidLoad(){
super.viewDidLoad()

让usersRef = self.ref.child(users)
usersRef.observeSingleEvent(of:.value,with:{snapshot in
为snapshot.children中的子节点{
let snap = child as!DataSnapshot
let userDict = snap.value as![String:Any]
self.usersArray.append(userDict)
}
self.tableView.reloadData()$



$ b $和$ table $委托方法

  func tableView(_ tableView:UITableView,numberOfRowsInSection section:Int) - > Int {
return self.usersArray.count
}

func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath) - > UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:HomeTableViewCell,for:indexPath)as! HomeTableViewCell

let userDict = self.usersArray [indexPath.row]
cell.text = userDict [name] as!字符串
//cell.imge = userDict [image] etc等

返回单元
}

现在...所有的说法。这是UserClass对象数组的完美用法,而不是字典。



这是一个起点....

  class UserClass {
var name =
var image =

func init(snap:DataSnapshot){
//从快照中填充变量


$ b $ user $ user $ { / pre>

不要复制和粘贴这个,因为有可能是拼写错误,但它应该指向你正确的方向。


I'm using firebase to make an iOS app. I want to retrieve all the users on my database and display their name and profile picture in a table view. Here is my code for my TableViewCell:

import UIKit
import FirebaseDatabase
import FirebaseAuth
import SDWebImage

class HomeTableViewCell: UITableViewCell {


    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var profileImageView: UIImageView!
    @IBOutlet weak var likeImageView: UIImageView!
    @IBOutlet weak var messageImageView: UIImageView!
    @IBOutlet weak var likeCountButton: UIButton!

    var homeVC: HomeViewController?
    var postReference: DatabaseReference!

    var post: UserFile?{
        didSet {
            updateView()
        }
    }

    var user: UserFile? {
        didSet {
            updateUserInfo()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        nameLabel.text = ""

        let berryTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleLikeTap))

        likeImageView.addGestureRecognizer(berryTapGesture)
        likeImageView.isUserInteractionEnabled = true

    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    func updateView() {
        if let photoURL = post?.picURL {
            profileImageView.sd_setImage(with: URL(string: photoURL))
        }

        API.Post.REF_POSTS.child(post!.id!).observeSingleEvent(of: .value, with: { postSnapshot in
            if let postDictionary = postSnapshot.value as? [String:Any] {
                let post = UserFile.transformPost(postDictionary: postDictionary, key: postSnapshot.key)
                self.updateLike(post: post)
            }
        })
        API.Post.REF_POSTS.child(post!.id!).observe(.childChanged, with: { snapshot in
            if let value = snapshot.value as? Int {
                self.likeCountButton.setTitle("\(value) berries", for: .normal)
            }
        })
    }

    func updateLike(post: UserFile) {
        let imageName = post.berries == nil || !post.isBerried! ? "berry" : "berrySelected"
        likeImageView.image = UIImage(named: imageName)

        // display a message for berries
        guard let count = post.berryCount else {
            return
        }

        if count != 0 {
            likeCountButton.setTitle("\(count) berries", for: .normal)
        } else if post.berryCount == 0 {
            likeCountButton.setTitle("Be the first to Like this", for: .normal)
        }
    }

    func incrementberries(forReference ref: DatabaseReference) {
        ref.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
            if var post = currentData.value as? [String : AnyObject], let uid = Auth.auth().currentUser?.uid {
                var berries: Dictionary<String, Bool>
                berries = post["berries"] as? [String : Bool] ?? [:]
                var likeCount = post["berryCount"] as? Int ?? 0
                if let _ = berries[uid] {
                    // Unlike the post and remove self from stars
                    likeCount -= 1
                    berries.removeValue(forKey: uid)
                } else {
                    // Like the post and add self to stars
                    likeCount += 1
                    berries[uid] = true
                }
                post["berryCount"] = likeCount as AnyObject?
                post["berries"] = berries as AnyObject?

                currentData.value = post

                return TransactionResult.success(withValue: currentData)
            }
            return TransactionResult.success(withValue: currentData)
        }) { (error, committed, snapshot) in
            if let error = error {
                print(error.localizedDescription)
            }

            if let postDictionary = snapshot?.value as? [String:Any] {
                let post = UserFile.transformPost(postDictionary: postDictionary, key: snapshot!.key)
                self.updateLike(post: post)
            }
        }
    }

    func handleLikeTap() {
        postReference = API.Post.REF_POSTS.child(post!.id!)
        incrementberries(forReference: postReference)
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        profileImageView.image = UIImage(named: "industribune-default-no-profile-pic")
    }

    func updateUserInfo() {
        nameLabel.text = user?.username
        if let photoURL = user?.profileImageURL {
            profileImageView.sd_setImage(with: URL(string: photoURL), placeholderImage: UIImage(named: "industribune-default-no-profile-pic"))
        }
    }


}

I am displaying this cell on my HomeViewController:

import UIKit
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import Firebase

class HomeViewController: UIViewController {


    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!

    var posts = [UserFile]()
    var users = [UserFile]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // for performance set an estimated row height
        tableView.estimatedRowHeight = 1
        // but also request to dynamically adjust to content using AutoLayout
        tableView.rowHeight = UITableViewAutomaticDimension

        //tableView.delegate = self
        tableView.dataSource = self

        loadPosts()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadPosts() {
        activityIndicatorView.startAnimating()

        API.User.observePosts { (newPost) in
            guard let userID = newPost.uid else { return }
            self.fetchUser(uid: userID, completed: {
                // append the new Post and Reload after the user
                // has been cached
                self.posts.append(newPost)
                self.activityIndicatorView.stopAnimating()
                self.tableView.reloadData()
            })
        }
    }

    func fetchUser(uid: String, completed: @escaping () -> Void) {

        API.User.observeUser(withID: uid) { user in
            self.users.append(user)

            completed()
        }
    }


}

extension HomeViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell

        cell.post = posts[indexPath.row]
        cell.user = users[indexPath.row]
        cell.homeVC = self

        return cell
    }

}

I have a lot of craziness going on in my project so let me know if you have any questions and what I'm doing wrong. If it's too complicated to understand I'm ready to erase everything and start over too.

And I do honestly think that I followed all the guidelines to ask a question so don't like shut this question down or something.

解决方案

That's a lot of code. Try this super reduced example. For this, the users node only stores the name as a child node but it could also have an image, email, address, etc.

Example users node

users
  uid_0:
     name: "Bert"
  uid_1:
     name: "Ernie"

and some code

var usersArray = [ [String: Any] ]()  //an array of dictionaries.

class ViewController: UIViewController {
    //set up firebase references here
   override func viewDidLoad() {
        super.viewDidLoad()

        let usersRef = self.ref.child("users")
        usersRef.observeSingleEvent(of: .value, with: { snapshot in
         for child in snapshot.children {
              let snap = child as! DataSnapshot
              let userDict = snap.value as! [String: Any]
              self.usersArray.append(userDict)
         }
         self.tableView.reloadData()
   })

and the tableView delegate methods

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.usersArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell

    let userDict = self.usersArray[indexPath.row]
    cell.text = userDict["name"] as! String
    //cell.imge = userDict["image"] etc etc

    return cell
}

Now... that all being said. This is the perfect use for an array of UserClass objects instead of the dictionaries.

Here's a starting point....

class UserClass {
   var name = ""
   var image = ""

   func init(snap: DataSnapshot) {
     //populate the vars from the snapshot
   }
}

var userClassArray = [UserClass]()

Don't copy and paste this as there are probably typos but it should point you in the right direction.

这篇关于如何从数据库中提取用户并使用Firebase将其列在表格视图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆