Search code examples
iosswiftdatabasefirebasedatamodel

I can't get the data from firebase database as a subclass object


My firebase data is as follows:

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

I read this with the following code

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()
    })

I have two datamodels 1 is match 2 is prediction

I can read code, date and starttime from database but with match object prediction data is not coming it says its nil, How can I get that data with match object?


Solution

  • You can set up the Model class as follows

    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?
    }
    

    In your ViewController you can add the below code

        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)