Get single elements from Firestore Document - swift

How can I get single items from my Document in Firebase?
I can get all elements with this code:
let key = UserDefaults.standard.value(forKey: "uid") as! String
let docRef = firebaseDB.collection("user").document(key)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:))
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
I only wish to get the name and phone number. How can I filter my result?

FirebaseFirestore has a handy way of caching single documents:
First, you need to specify the document by it's ID:
let key = UserDefaults.standard.value(forKey: "uid") as? String ?? "Null" // Unique user key
let docRef = db.collection("user").document(key)
Get the document:
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let docData = document.data()
// Do something with doc data
} else {
print("Document does not exist")
}
}
Access the doc data:
let status = docData!["phone"] as? String ?? ""

Related

How can i retrieve data from a collection if the condition is set firestore swift

Here is my code pls help
My target is to retrieve a list of channels that contain uid within Subscriptions collection.
func getUserSubscriptions(uid: String) {
db.collection("Channels").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
//No documents found
return
}
for document in querySnapshot!.documents {
document.reference.collection("Subscribers").whereField("user_id", isEqualTo: uid).addSnapshotListener { (querySnapshot, error) in
guard (querySnapshot?.documents) != nil else {
//No documents found
return
}
//I want to get Channels that only contain uid withing it's Subscribers collection, but unfortunately it only gets the whole Channels, please help.
DispatchQueue.main.async {
self.channels = documents.map { d in
return Channels(id: d.documentID, channel_id: d["channel_id"] as! String?, channel_name: d["channel_name"] as? String ?? "", creator: d["creator"] as? String ?? "")
}
}
}
}
}
}
Pls help I got stuck here.

How to display string array from Firebase in tableview?

How to display the result of this firebase array in a table?
I can see the result in the console, but I would like to display in a table all the elements of the firebase array?
func getMaterie() {
let db = Firestore.firestore()
let docRef = db.collection("DegreeCourses").document(userInfo.Tipocorso)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let materieArray = document.get("Materie") as? [[String: String]]
print(materieArray!)
}
}
}
}
Console

firestore fetch subcollection

I'm trying to fetch subcollection of my users document with code below
func readData(){
let userId = Auth.auth().currentUser?.uid
self.db.collection("users/\(userId)/saved").getDocuments { (snapshot, err) in
if let err = err {
print("err")
}
if let userId != nil {
for document in snapshot!.documents {
let docId = document.documentID
let cty = document.get("city") as! String
let ccode = document.get("code") as! String
let countr = document.get("country") as! String
print(cty, ccode, countr,docId)
}
}
}
but my code doesn't print anything, I don't understand the problem, documents exsist, see picture below
You're using illegal syntax with the userId check in the snapshot return but the logic flow is the bigger problem. I would recommend you check if the user is signed in before grabbing the subcollection and checking if there is a viable snapshot instead of checking the state of authentication.
func readData() {
guard let userId = Auth.auth().currentUser?.uid else {
return
}
db.collection("users/\(userId)/saved").getDocuments { (snapshot, error) in
guard let snapshot = snapshot else {
if let error = error {
print(error)
}
return
}
for doc in snapshot.documents {
guard let city = doc.get("city") as? String,
let code = doc.get("code") as? String,
let country = doc.get("country") as? String else {
continue // continue document loop
}
let docId = doc.documentID
print(city, code, country, docId)
}
}
}

Struggling with basic Swift logic (Working with constants, variables and loops)

I want to use 2 Strings that I get with those two "loops" from firebase and use them in another "loop" to upload them with a bunch of other Information.
My problem is, that I somehow can't get the values of fullname and pfp that I downloaded, into the upload to firebase.
Any ideas on how to solve this issue?
func sendToFire(){
let combined = "\(userID)" + "\(number)"
let docRef = db.collection("posts").document(combined)
let description = self.textPost.text
let nameRef = db.collection("users").document(userID)
var fullname = ""
var pfp = ""
if fireImage == nil {
nameRef.getDocument { (document, error) in
if let document = document{
fullname = document.get("fullname") as! String
}else{
print("Coulnt get fullname")
}
}
nameRef.getDocument { (document, error) in
if let document = document{
pfp = document.get("profileimage") as! String
}else{
print("Couldn't get profileimage")
}
}
docRef.getDocument { (document, error) in
if let document = document, document.exists {
print("Post ID already taken")
} else {
print("Post Document gets created")
self.db.collection("posts").document(combined).setData([
"description": description!,
"likes": self.likes,
"postType": 0,
"profileImage": pfp,
"time": self.date,
"uid": self.userID,
"username": fullname
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Post Document successfully written!")
}
}
}
}
}
}
Add document.exists in the if let
nameRef.getDocument { (document, error) in
if let document = document, document.exists{
fullname = document.get("fullname") as! String
}else{
print("Coulnt get fullname")
}
}
nameRef.getDocument { (document, error) in
if let document = document, document.exists{
pfp = document.get("profileimage") as! String
}else{
print("Couldn't get profileimage")
}
}
Check the actual key names in the response fullname and profileimage.

How to get the first name of the logged in User from firebase using Swiftui?

How to to get the first name of the current user which is logged in.
This is how my try looks like:
var ref: DatabaseReference!
ref = Database.database().reference()
let db = Firestore.firestore()
let userID = Auth.auth().currentUser?.uid
print(userID)
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["firstname"] as? String ?? ""
print(username)
// ...
}) { (error) in
print(error.localizedDescription)
}
Try the following:
let userId = Auth.auth().currentUser?.uid else { return }
let docRef = db.collection("users").document(userId)
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let name = document.get("firstname")
print("Cached document data: \(name)")
} else {
print("Document does not exist in cache")
}
}
You are using cloud firestore but in your code, you are using the Realtime database. You need to check the following docs related to cloud firestore:
https://firebase.google.com/docs/firestore/quickstart