【问题标题】:Retrieve firebase data from swift从 swift 中检索 firebase 数据
【发布时间】:2019-04-24 07:38:19
【问题描述】:

我正在尝试从 Firebase RealTime 数据库中检索数据,以便将其放在一个列表中,该列表将用于在 TableView 上显示数据。

我的问题是,即使我得到了一些数据,我也没有足够的知识来访问数组和其他 swift 对象。也许,我没有使用好方法来做我想做的事。

这是 Firebase 上的一行示例:

这是一个用 Swift 编写的函数,我正在尝试为每个行对象构建一个列表。

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

        }
    })
}

Xcode 工作区上的 lldb 显示:

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) 

能否请您帮我检索列表中的数据,我可以附加这些数据以在 tableview 上显示数据?谢谢。

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    试试这样的:

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

    【讨论】:

    • 非常感谢,这对我来说没问题。 :)
    【解决方案2】:

    您可以使用 swift 类代替。

    Swift 对象:

    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 方法

    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!)")
            })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多