ios - 在 TableView 单元格中显示来自 Firebase 的数据

标签 ios swift firebase firebase-realtime-database

我的一个 VC 中有以下代码(作为我较大项目的一部分)。我的 Firebase 数据库引用之一称为 Sell_Request。它有三个 child (namelatitudelongitude),但我只关心 name 的权利现在。

我正在尝试将它添加到一个字符串数组,并将它打印到控制台。我看到名称被打印到控制台,但我没有在单个单元格中打印名称。

感谢您的关注。

import UIKit
import Firebase
import FirebaseDatabase
import MapKit
import CoreLocation

class RequestVC: UITableViewController, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var sellerUserNames = [String]()

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "backToMain" {
            self.navigationController?.navigationBar.isHidden = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = manager.location?.coordinate {
            let databaseRef = FIRDatabase.database().reference()
            databaseRef.child("Sell_Request").queryOrderedByKey().observe(.childAdded, with: { (FIRDataSnapshot) in

                if let data = FIRDataSnapshot.value as? NSDictionary {
                    if let name = data[Constants.NAME] as? String {
                                self.sellerUserNames.append(name)
                                print(name)
                                }
                            }
                        })
                    }
                }


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



    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sellerUserNames.count
    }


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

        cell.textLabel?.text = sellerUserNames[indexPath.row]

        return cell
    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

最佳答案

在将名称附加到 sellerUserNames 数组后,您只需调用 tableView.reloadData(),将您的函数更改为此...

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = manager.location?.coordinate {
        let databaseRef = FIRDatabase.database().reference()

        sellerUserNames.removeAll()
        databaseRef.child("Sell_Request").queryOrderedByKey().observe(.childAdded, with: { (FIRDataSnapshot) in

            if let data = FIRDataSnapshot.value as? NSDictionary {
                if let name = data[Constants.NAME] as? String {
                            self.sellerUserNames.append(name)
                            print(name)
                            self.tableView.reloadData()
                            }
                        }
                    })
                }
            }

编辑

你想在哪里/什么时候调用 sellerUserNames.removeAll() 取决于你的代码和你的 TableView 的生命周期,但我已经编辑了上面的代码以将它添加到最重要的地方可能合适。

关于ios - 在 TableView 单元格中显示来自 Firebase 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42428381/

相关文章:

ios - Segue 到 UITableViewController 覆盖导航栏

ios - 如何在 Xcode11 的 Swift 中随机播放数组中的音频文件?

ios - 模态关闭后 viewWillAppear 没有更新旋转

swift - 您可以强制使用两种类型的泛型来确保这些类型不相同吗?

ios - 如何在Sprite Kit中检测碰撞?

java - 数据库中的值每天加一

ios - ios(Xamarin)中的奇怪行为UIButton

ios - meteor + Cordova + iOS : unallowed to upload file

angular - 根据官方文档在app.module中导入@angular/fire时输入错误?

node.js - Firebase 云消息传递成功 sendToDevice 但没有通知