我正在尝试从Firestore数据库中的集合中检索数据。但是在打印检索到的数据时,它与我期望的格式不符。
这是我的代码,用于检索以下数据:
let db = Firestore.firestore()
func loadEvents() -> [Event] {
var events = [Event]()
let decoder = JSONDecoder()
db.collection("Events").addSnapshotListener { QuerySnapshot, error in
guard let documents = QuerySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
for doc in documents {
let dict = doc.data()
if let data = try? JSONSerialization.data(withJSONObject: dict, options: []) {
let event = try? decoder.decode(Event.self, from: data)
events.append(event!)
print(events) // Prints stuff like [Envy.Event] ...
}
}
// let events = documents.map {$0.data()}
}
return events
}
到达print(events)
时,它会打印出[Envy.Event]
[Envy.Event, Envy.Event]
[Envy.Event, Envy.Event, Envy.Event]
[Envy.Event, Envy.Event, Envy.Event, Envy.Event]
之类的内容,该数据不适合用于操纵。我什至不了解这种格式;有人可以帮我吗?
答案 0 :(得分:0)
您打印错误。您正在打印创建的整个模型类,则需要引用该类中的对象,例如。
print(events.name) // use the object name you have in your class
print(events.location) // use the object name you have in your class
要将数据添加到数组中 示例代码:
db.collection("Events").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
let list = Event(name: document.get("yourKeyName") as? String,location: document.get("yourAnotherKeyName") as? String)
events.append(list)
print(event.name)
print(event.location)
}
}
}
希望这会有所帮助