Aufra
Aufra

Reputation: 13

Retrieve firebase data from swift

I'm trying to retrieve data from a Firebase RealTime database, in order to put it on a list which will be used to display data on a TableView.

My problem is that even if I get some data, I haven't enough knowledge to access on arrays and other swift objects. Perhaps, I'm not using the good way to do what I want.

Here is an example of a row on Firebase :

enter image description here

Here is a function written in Swift in which I'm trying to build a list for each row object.

func displayStationsUsingSearch(){


    let station = self.stationName
    let CP = Int(self.searchedCP!)

    // create searchRef or queryRef you name it
    let stationsRef = Database.database().reference().child("Stations")
    stationsRef.observeSingleEvent(of: .value, with: { (snapshot) in
        print(snapshot)
        /*if snapshot.value is NSNull {
            print("not found")
        } else {
            // yes we got the user
            let id = snapshot.value as! Int
        }*/
        for child in snapshot.children {

            stationsRef.queryOrdered(byChild: "marque")
                .queryEqual(toValue: "TOTAL ACCESS")
                .observe(.value, with: { snap in

                    if let dict = snap.value as? [String: AnyObject] {
                        /*self.stationItem!.nomStation = dict["nomStation"] as! String
                        self.stationItem!.adresse = dict["adresse"] as! String
                        self.stationItem!.codePostal = dict["codePostal"] as! String
                        self.stationItem!.ville = dict["ville"] as! String
                        self.stationItem!.marque = dict["marque"] as! String
                        self.stationItem!.pays = dict["pays"] as! String
                        self.stationItem!.commentaire = dict["commentaire"] as! String
                        self.stationItem!.coordGPS = dict["coordGPS"] as! String*/
                        print(dict["nomStation"] as! String)
                    }
            })

        }
    })
}

The lldb on Xcode workspace displays that :

Printing description of child:
Snap (-LdA6X8CfNY3bsPni31U) {
"DIESEL EXCELLIUM" = 0;
"DIESEL ULTIMATE" = 0;
GAZOLE = 0;
GPL = 0;
SP95 = 0;
"SP95 E10" = 0;
SP98 = 0;
SUPER = 0;
adresse = "RN1 Direction Moisselles";
codePostal = 95570;
commentaire = "";
coordGPS = "";
createdAt = "31/07/2018";
heureDebut = "";
heureFin = "";
id = 0;
marque = ESSO;
modifiedAt = "23/04/2019 18:53";
nomStation = "ESSO Moisselles";
pays = "";
saufJour = "";
services = "";
typeRoute = "";
ville = Moisselles;
}
(lldb) 

Could you please help me to retrieve data on a list that I could append to display data on tableview ? Thank you.

Upvotes: 1

Views: 2169

Answers (2)

Adekola Akano
Adekola Akano

Reputation: 169

You can use a swift Class Instead.

Swift Object:

import Foundation

class FirebaseTransactionData : NSObject{

    var customer : FirebaseTransactionDataCustomer!
    var driver : FirebaseTransactionDataCustomer!
    var status : String!

    init(fromDictionary dictionary: [String:Any]){
        status = dictionary["status"] as? String
        if let customerData = dictionary["customer"] as? [String:Any]{
            customer = FirebaseTransactionDataCustomer(fromDictionary: customerData)
        }
        if let driverData = dictionary["driver"] as? [String:Any]{
            driver = FirebaseTransactionDataCustomer(fromDictionary: driverData)
        }
    }
}

class FirebaseTransactionDataCustomer : NSObject{

    var lat : Double!
    var longField : Double!

    init(fromDictionary dictionary: [String:Any]){
        lat = dictionary["lat"] as? Double
        longField = dictionary["lng"] as? Double
    }
}

Firebase Method

ref.observe(DataEventType.value, with: { (snapshot) in
            let value = snapshot.value as? [String:Any]
            let datt = FirebaseTransactionData(fromDictionary: value!)
            print("snapshot \(datt.status!)")
            print("snapshot \(datt.customer.lat!)")
        })

Upvotes: 0

Aleksey Shevchenko
Aleksey Shevchenko

Reputation: 1241

Try something like that:

Database.database().reference()
  .child("Stations").
  observeSingleEvent(of: .value, with: { (snapshot) in 
    guard let value = snapshot.value as? [String: Any] else {
      return
    }

    var stations = [Station]()
    for (key, value) in values {
      guard let station = value as? [String: Any],
          let adresse = station["adresse"] as? String,
          let codePostat = station["codePostat"] as? String else {
              continue
          }
          stations.append(Station(adresse: adresse, codePostat: codePostat))
    }

    // if you have some completion return retrieved array of stations
    completion(stations)
})

struct Station {

  private let adresse: String
  private let codePostat: String

  init(adresse: String, codePostat: String) {

    self.adresse = adresse
    self.codePostat = codePostat
  }
}

Upvotes: 1

Related Questions