我无法从Firebase数据库获取数据作为子类对象

时间:2018-11-27 12:32:07

标签: ios swift database firebase datamodel

我的firebase数据如下:

Matches
items
  platinium
  standard
   -LQTnujHvgKsnW03Qa5s
      code: "111"
      date: "27/11/2018"
      predictions
              -0
                prediction: "Maç Sonucu 1"
                predictionRatio: "2"
      startTime: "01:01"

我用以下代码阅读了

databaseHandle = ref.observe(.childAdded, with: { (snapshot) in
        if let matchDict = snapshot.value as? Dictionary<String, AnyObject> {
            let m_key = snapshot.key
            let m = Match(matchKey: m_key, matchData: matchDict)
            self.matches.append(m)
        }
        self.matchesTableView.reloadData()
    })

我有两个数据模型 1个符合 2是预测

我可以从数据库中读取代码,日期和开始时间,但是没有匹配对象预测数据,这说明它为零,如何与匹配对象获取数据?

1 个答案:

答案 0 :(得分:0)

您可以按以下步骤设置Model类

class ListModel: NSObject {
var UID:String?
    var Code:String?
    var Date:String?
    var PredictionsArr:[PredictionsObj]?
    var StartTime:String?
}

class PredictionsObj : NSObject {
    var Prediction : String?
    var PredictionRatio : String?
}

在您的ViewController中,您可以添加以下代码

    var ListArr = [ListModel]()

        let ref = Database.database().reference().child("Matches").child(“items”).child(“standard”)
        ref.observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            guard let dictionary = snapshot.value as? [String : AnyObject] else {
                return
            }

            let Obj = ListModel()
            Obj.UID = snapshot.key
            Obj.Code = dictionary["code"] as? String
            Obj.Date = dictionary["date"] as? String
            Obj.StartTime = dictionary["startTime"] as? String

            let myPredictionsArr  = dictionary["predictions"] as? NSArray
            var myPredictionsObj = [PredictionsObj]()
            if myPredictionsArr != nil{
                for dict in myPredictionsArr as! [[String: AnyObject]]  {
                    let detail = PredictionsObj()
                    detail.Prediction = dict["prediction"] as? String
                    detail.PredictionRatio = dict["predictionRatio"] as? String
                    myPredictionsObj.append(detail)
                }
            }
            Obj.PredictionsArr = myPredictionsObj

            self.ListArr.append(Obj)
            self.ListTV.delegate = self
            self.ListTV.dataSource = self
            self.ListTV.reloadData()
        }, withCancel: nil)