Reputation: 11
I'm trying to do my first query in firestone but I'm not able to see results properly. Could someone help me? Please take a look at the code and picture
import UIKit
import Firestore
import Firebase
class ViewControllerFirestone: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
simpleQueries()
}
private func simpleQueries() {
let db = Firestore.firestore()
let citiesRef = db.collection("cities")
let myQuery = citiesRef.whereField("state", isEqualTo: "CA")
print ("My query is retrieving this : \(myQuery)")
}
}
Upvotes: 1
Views: 554
Reputation: 12405
After you construct your query, you have to then query the database--that's how you get data back. The data that's returned is a custom Firestore object (QuerySnapshot
) that has a number of properties, one of which is documents
which is an array of another custom Firebase object (FIRDocumentSnapshot
). From that property is where your data resides. The FIRDocumentSnapshot
object has a method called get()
which can extract data for you (you can also use more idiomatic dictionary syntax and not use the get()
method). Read the Firestore documentation online; it's often painfully terse but it works.
import UIKit
import FirebaseFirestore
class ViewControllerFirestone: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
simpleQueries()
}
private func simpleQueries() {
let db = Firestore.firestore()
let citiesRef = db.collection("cities")
let myQuery = citiesRef.whereField("state", isEqualTo: "CA")
myQuery.getDocuments { (snapshot, error) in
guard let snapshot = snapshot,
error == nil else { // error
return print("database error: \(error!)")
}
guard !snapshot.isEmpty else { // no data
return print("no data")
}
// data fetched, loop through documents
for doc in snapshot.documents {
guard let stateProperty = doc.get("state") as? String else {
continue // continue loop
}
print(stateProperty)
}
}
}
}
As a side note, this is a good place to use dispatch queues to handle your results in the background as the data returned by Firestore will always be on the main thread. This example does not use queues.
Upvotes: 1