ios - Firebase/Swift - 从 Firebase 输出数据出错

标签 ios swift uitableview firebase firebase-realtime-database

我在正确从 Firbase 输出数据时遇到问题。我花了很多时间并尝试了很多不同的方法来做到这一点,创建不同的数据结构等,但我总是会崩溃或为零输出。我当前的代码正在运行并将数据从 firebase 输出到 TableView 中,但是数组未对齐,并且特定用户的一个数组中的字段与另一个数组中的字段不相关,这是不正确的。

我想有一种更好的方法可以做到这一点,因此任何帮助或正确方向的观点将不胜感激。另外请对我宽容点,我知道这一点:)

这是我的 firebase 结构:

这是我的租赁模型:

struct RentalObjects {

    var title: [String : AnyObject] = [:]
    var rentalType: [String : AnyObject] = [:]
    var dateAval: [String : AnyObject] = [:]
    var location: [String : AnyObject] = [:]
    var price: [String : AnyObject] = [:]
    var bond: [String : AnyObject] = [:]
    var pets: [String : AnyObject] = [:]
    var descripton: [String : AnyObject] = [:]

}

这是我的 VC 输出到 TableView 的代码:

import UIKit
import FirebaseDatabase


class RentalTableViewVC: UIViewController, UITableViewDataSource, UITableViewDelegate{

    @IBOutlet weak var rentalImage: UIImageView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var rentalTitle: UILabel!
    @IBOutlet weak var rentalPrice: UILabel!


    var rentalsObject = RentalObjects()
    var databaseRef:DatabaseReference?
    var handle: DatabaseHandle?

    var arrayOfTitles = [String?]()
    var arrayOfBond = [String?]()



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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

        for (_, value) in rentalsObject.title {
            arrayOfTitles.append(value as? String)

        }

        for (_, value) in rentalsObject.bond {

            arrayOfBond.append(value as? String)

        }


        cell.textLabel?.text = ("Title: \(String(describing: arrayOfTitles[indexPath.row]!)), Bond: \(String(describing: arrayOfBond[indexPath.row]!))")



        return cell
    }


    @IBAction func backPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
    super.viewDidLoad()


        databaseRef = Database.database().reference().child("Rentals")
        databaseRef?.observe(DataEventType.value, with: { (snapshot) in

            for rentals in snapshot.children.allObjects as! [DataSnapshot] {





        switch rentals.key {

                case "title" :
                    let titleObj = rentals.value as! [String : AnyObject]

                    self.rentalsObject.title = titleObj

                case "rentalType":
                    let rentalTypeObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.rentalType = rentalTypeObj

                case "dateAval":
                    let dateAvalObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.dateAval = dateAvalObj
                case "location":
                    let locationObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.location = locationObj

                case "price" :
                    let priceObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.price = priceObj

                case "bond" :
                    let bondObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.bond = bondObj

                case "pets" :
                    let petsObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.pets = petsObj

                case "description":
                    let desObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.descripton = desObj

                default:
                    break

                }

            }
            self.tableView.reloadData()
        })

    }

}

最佳答案

使用 .childAdded 代替 .value。 ChildAdded 获取每个对象,而 Value 获取所有对象。您应该从“cellForRowAr”方法中删除 for 循环。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

       cell.textLabel?.text = ("Title: \(String(describing: arrayOfTitles[indexPath.row]!)), Bond: \(String(describing: arrayOfBond[indexPath.row]!))")

       return cell
}



override func viewDidLoad() {
   super.viewDidLoad()

   databaseRef = Database.database().reference().child("Rentals")
   databaseRef?.observe(.childAdded, with: { (snapshot) in

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

          switch snapshot.key {

             case "title" :
             _ = dictionary.map{self.arrayOfTitles.append($0.value as? String)}
             case "rentalType":

             case "dateAval":

             case "location":

             case "price" :

             case "bond" :
             _ = dictionary.map{self.arrayOfBond.append($0.value as? String)}
             case "pets" :

             case "description":

             default:
                break
           }
        }
     })
     self.tableView.reloadData()
}

关于ios - Firebase/Swift - 从 Firebase 输出数据出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259457/

相关文章:

json - 将回调 Swift JSON AnyObject 转换为 NSDictionary

ios - 不为特定设备下载点播资源

ios - UITableView 中的自定义单元格在滑动后立即移动以进行编辑

UITableViewController 不响应键盘

ios - 为什么这些VM :UITableViewCellSelectedBackground(CALayer) come out for every UITableViewCell in Allocations?

ios - UITableViewCell 加载错误的 CAShapeLayer

ios - 为导航标题设置图像在横向模式下无法正常工作

ios - 迪尔德 : lazy symbol binding failed: Symbol not found: _objc_loadWeak

ios - SpriteKit : child does not rotate with parent SKNode

ios - 自定义 tableview 单元格的问题。自定义 tableview 单元格内的 Collectionview 未根据单元格的高度进行调整