gpt4 book ai didi

swift - 从 swift 检索 firebase 数据

转载 作者:行者123 更新时间:2023-11-30 10:45:31 24 4
gpt4 key购买 nike

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

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

以下是 Firebase 上的行示例:

enter image description here

这是一个用 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)

您能帮我检索列表中的数据吗?我可以附加该列表以在表格 View 上显示数据?谢谢。

最佳答案

尝试类似的事情:

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

关于swift - 从 swift 检索 firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55824700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com