How to access a specific field from Cloud FireStore Firebase in Swift
There is no API that fetches just a single field from a document with any of the web or mobile client SDKs. Entire documents are always fetched when you use getDocument(). This implies that there is also no way to use security rules to protect a single field in a document differently than the others.
If you are trying to minimize the amount of data that comes across the wire, you can put that lone field in its own document in a subcollection of the main doc, and you can request that one document individually.
See also this thread of discussion.
It is possible with server SDKs using methods like select(), but you would obviously need to be writing code on a backend and calling that from your client app.
Access Fields of Firebase Firestore Document In Swift and ios 14?
To get values of fields from the retrieved document you can this:
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
let data = document.data()
let username = data!["username"]! as? String ?? ""
let fieldName = data!["fieldName"]! as? String ?? ""
print(username)
} else {
print("Document does not exist")
}
}
How do I display certain field from a Firestore document
Both reading and access control are on a per-document basis, so you can't read only a single field from a document.
You can read the entire document, and display a single field of course, but you'll still be reading the entire document into the application.
If you don't want to do that (for example: because of access permissions, or to save bandwidth), consider creating an additional collection where each document has the same key, but only contains the field(s) for this use-case.
How to get specific field data with Firestore get request?
There are two ways for accessing specific fields in Firestore documents:
- The
data()
method returns a dictionary mappingString
toAny
. You can read attributes like so:
let data = queryDocumentSnapshot.data()
let title = data["title"] as? String ?? ""
let author = data["author"] as? String ?? ""
let numberOfPages = data["pages"] as? Int ?? 0
- You can use Firestore's Codable support to map documents to Swift structs / classes with a one-liner, like this:
let book = try? queryDocumentSnapshot.data(as: Book.self)
Read more about these here and here, respectively.
I'd recommend extracting any data access code into a view model or a store. The articles I linked to show how to do this. This will make your code easier to read, less error-prone, and more maintainable.
How to get the field values in firebase cloud database?
You can get a single field by doing document.get("favoriteAritsts")
(notice your typo in favoriteAritsts
in your screenshots.
You can also do document.data()["favoriteAritsts"]
Both of the above will give you a return type of Any?
so you would need to do any optional cast of either one with as? [String]
:
let array = document.get("favoriteAritsts") as? [String]
Accessing a specific document field with Swift (Firestore)
for document in querySnapshot!.documents {
if let content = document.data()["content"] as? String {
print(content)
}
}
How to fetch a single Field from a Firestore document in a collection from Firebase?
I am trying to fetch only a Map field stored in a document of Firestore collection instead of fetching the whole document which is obviously more time taking and bandwidth-consuming.
There is no way you can do that. All Firestore listeners fire on the document level. This means that you cannot only get the value of a Map field from a document. It's the entire document or nothing. That's the way Firestore works, and unfortunately, we cannot change that.
Is there any way I can get just a particular field of any data type from a Firestore document?
No. However, if you only want to read the value of a single property then you should consider storing only that property in a document. Or store that single property in the Realtime Database. This practice is called denormalization, and it's a quite common practice when it comes to NoSQL databases.
How to access a firebase field in swift?
The Auth.auth().currentUser
in your code determines the user that is signed in with Firebase Authentication.
The screenshot in your question shows a document in the Cloud Firestore database.
While both products are part of Firebase, you can't access documents in Firestore through the Firebase Authentication API.
If you want to access the document in your screenshot, use the Firestore API that is documented here.
To load the document for the user that is currently signed in to Firebase Authentication, that'd be something like:
let user = Auth.auth().currentUser
let uid = user.uid
let docRef = db.collection("users").document(uid)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let username2 = document.get("username")
...
} else {
print("Document does not exist")
}
}
Update* I now noticed that you have the UID of the user inside the document. In that case you need to use a query to find the document(s) that match the UID value:
db.collection("users").whereField("uid", isEqualTo: uid)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
let username2 = document.get("username")
self.username?.text = username2 as? String
}
}
}
Since in this case there may be multiple documents with the UID, so you'll have to loop and deal with that.
Please also read the links that I added, as most of this is copy/paste from there and my Swift knowledge is not great.
Cloud Firestore & Swift - Retrieve Document & assign fields to variables for processing
I would recommend this way:
let docRef = db.collection("ask").document(uid!)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
let data = document.data()
let q1 = data!["q1"]! as? Bool ?? true
if q1 == false {
//false code
} else {
//true code
}
} else {
print("Document does not exist")
}
}
Related Topics
Starting Iphone App Development in Linux
Detect If the Device Is Iphone X
This Certificate Has an Invalid Issuer Apple Push Services
How to Apply Gradient to Background View of iOS Swift App
How to Create a Multiline Textfield in Swiftui
Set a Default Font For Whole iOS App
How to Get Current Location from User in Ios
How to Use Timer (Formerly Nstimer) in Swift
The Best Way to Remove Duplicate Values from Nsmutablearray in Objective-C
Uploading File With Parameters Using Alamofire
Background Location Services Not Working in iOS 7
Wait For Firebase to Load Before Returning from a Function
Returning Method Object from Inside Block
How to Use Background Thread in Swift
Making a Uitableview Scroll When Text Field Is Selected
What Is "Constrain to Margin" in Storyboard in Xcode 6