首页 文章

你如何从数组中追加一个随机的USER?

提问于
浏览
-3

我当然正在为我的项目使用Firebase . 我有一堆“用户”的数据库,我已将所有用户以及他们的“用户名”返回到我的简单tableView中 . 我想知道,我如何从用户数组中选择一个随机用户,并在我的viewDidLoad中调用我的fetchUser()函数时附加一个用户?这是我的tableView代码和我的Firebase代码 . 任何帮助将受到高度赞赏 . 谢谢!

import UIKit

private let reuseIdentifier = "Cell"

class NewMessageController: UITableViewController {

    var users = [User]()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Chat"

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)

        fetchUser()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupViewWillAppear()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return users.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)

        let user = users[indexPath.row]
        cell.textLabel?.text = user.username

        return cell
    }
}

    func fetchUser() {

    let ref = FIRDatabase.database().reference().child("users")

    ref.observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {

            let user = User()

            user.username = dictionary["username"] as? String
            user.profile_image_url = dictionary["profile_image_url"] as? String

            self.users.append(user)

            DispatchQueue.main.async {

                self.tableView.reloadData()
            }
        }

    }, withCancel: nil)
}

1 回答

  • 1

    将它们全部加载到一个数组中,并生成0范围内的随机数 .

    indexUser = Int(arc4random_uniform(users.count))
    

    然后更改 fetchUsers() 以返回单个用户,并且

    return self.users[indexUser]
    

    以下是您可能会如何更改 fetchUser

    func fetchUser() -> User {
    
        let ref = FIRDatabase.database().reference().child("users")
    
        ref.observe(.childAdded, with: { (snapshot) in
    
            if let dictionary = snapshot.value as? [String: AnyObject] {
    
                let user = User()
    
                user.username = dictionary["username"] as? String
                user.profile_image_url = dictionary["profile_image_url"] as? String
    
                self.users.append(user)
            }
    
            if self.users.count > 0
            {
                // You now have an array of users, so pick one
                return  self.users[Int(arc4random_uniform(self.users.count))]
            }
            else
            {
                return nil
            }
    
        }, withCancel: nil)
    }
    

    如果要继续在tableView中显示所有用户,则需要在拥有所选用户后重新加载表

相关问题