ios - 从 firebase 数据库中检索计算平均值

标签 ios swift uitableview firebase firebase-realtime-database

我正在创建一个 iOS 应用程序,它为每个地方使用地名和评级。我已经让这件事成功了。我的意思是,我将数据保存到我的数据库中,我也可以读取它们。唯一的问题是,当我阅读它们时,我希望它们通过计算每个位置的平均值来加载到我的 tableviewcell 上。查看屏幕截图,如果您不明白什么,请让我编辑答案。

表格 View

TableView

火力基地

Firebase

我将数据加载到 tableview 的代码

import UIKit
import FirebaseDatabase

class PlacesTableViewController: UITableViewController {

    //MARK: Properties
    @IBOutlet weak var placesTableView: UITableView!
    var dbRef:FIRDatabaseReference?
    var places = [Places]()
    private var loadedLabels = [String: String]()
    private var loadedRatings = [String: Int]()
    override func viewDidLoad()
    {
        super.viewDidLoad()

        dbRef = FIRDatabase.database().reference()

        // Loads data to cell.
        loadData()
    }
    override func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {   
        //return the number of rows
        return places.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        // Table view cells are reused and should be dequeued using a cell identifier.


        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlacesTableViewCell  else {
            fatalError("The dequeued cell is not an instance of PlacesTableView Cell.")
        }

        let place = places[indexPath.row]

        cell.placeLabel.text = place.name
        cell.ratingControl.rating = place.rating

        return cell

    }
    private func loadData()
    {
        dbRef!.observe(.childAdded, with: {
            (placeSnapshot) in
            //print("Adding place \(placeSnapshot.key)...")

            let labels = placeSnapshot.childSnapshot(forPath: "placeLabel")

            for (key, label) in labels.value as! [String: String] {
                self.updatePlace(key, label: label)
            }
            let ratings = placeSnapshot.childSnapshot(forPath: "rating")
            for (key, rating) in ratings.value as! [String: Int] {
                self.updatePlace(key, rating: rating)
            }
        })
 }

    private func updatePlace(_ key: String, label: String? = nil, rating: Int? = nil)
    {
        if let label = label {
            loadedLabels[key] = label

        }
        if let rating = rating {
            loadedRatings[key] = rating
        }
        guard let label = loadedLabels[key], let rating = loadedRatings[key] else {
            return
        }
        if let place = Places(name: label, rating: rating) {
            places.append(place)
            placesTableView.reloadData()
        }
    }

}

快速放置

import UIKit

class Places {

    //MARK: Properties

    var name: String
    var rating: Int

    //MARK:Types

    struct PropertyKey {
        static let name = "name"
        static let rating = "rating"
    }

    //MARK: Initialization

    init?(name: String, rating: Int) {
        // Initialize stored properties.
        self.name = name
        self.rating = rating

        // Initialization should fail if there is no name or if the rating is negative.
        // The name must not be empty
        guard !name.isEmpty else {
            return nil
        }

        // The rating must be between 0 and 5 inclusively
        guard (rating >= 0) && (rating <= 5) else {
            return nil
        }

    }

}

最佳答案

据我了解,您希望为您的应用程序使用四舍五入的 double 而不是 double 。只需更改 loadData() 函数中的代码,它就会为您工作。您还可以像以前一样调用 updatePlace()。请批准 Jay 的回答,他写了代码。

private func loadData()
{
    dbRef!.observe(.childAdded, with: {
        (placeSnapshot) in
    let parentRef = self.dbRef?.child(placeSnapshot.key)
    let ratingRef = parentRef?.child("rating")
    ratingRef?.observe(.value, with: { snapshot in
        let count = snapshot.childrenCount
        var total: Double = 0.0
        for child in snapshot.children {
            let snap = child as! FIRDataSnapshot
            let val = snap.value as! Double
            total += val
        }
        let average = total/Double(count)
        print("Average for \(placeSnapshot.key) = \(Int(round(average)))")

        self.updatePlace("" , label: placeSnapshot.key, rating: Int(round(average)))

    })
    })

}

关于ios - 从 firebase 数据库中检索计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44023455/

相关文章:

ios - 为什么滑动手势识别器只能工作一次?

ios - 在 swift 5 中使用 UITabBar.appearance().bar 样式崩溃

ios - 如何使应用角标(Badge)编号为0? (使用解析和快速)

iphone - objective-c : How to highlight the first cell in table view when view loads?

ios - 为委托(delegate)保留和释放对象

ios - 当 iPhone 方向改变时更改 UIViews 位置

ios - 如何单击 UITabBarItem 并显示新的 ViewController?

ios - UIView 背景色比 UICollectionView 背景色深

iphone - 为 uitableview 创建自定义删除按钮

ios - Objective c-只有特定的 UILabel 在 UITableView 中被编辑