Guten Tag,
i'm uploading some text to firebase through my iOS Application, but i can't find a code, where i can give the App User not a random ID, but maybe the email for the id to upload or Name. I hope you understand what i mean.
Current Code:
let logininit : [String : AnyObject] = ["text4" : text4!, "text5" : text5!, "text6" : text6!]
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("Logins").childByAutoId().setValue(logininit)
Now i want to remove this childByAutoID, and set it to, how i said, email or name of the user.
Firebase Database
EDIT
Resolved this Problem: databaseRef.child("Logins").child(The Email That You Want Here).setValue(logininit)
I think I understood what you meant, but I don't see reasons for you to do that. Usually when you have a new entry on some entity, you usually gives it a unique ID (UUID). So, I think if you use child(The Email That You Want Here), should work as you want:
databaseRef.child("Logins").child(The Email That You Want Here).setValue(logininit)
Related
What I want to do is to make a top header in the app with the name of the user displayed in a label. I know everything to do this except how to reference their name. To give more clarity this is what I want (even though this doesn't work in the newest version of xcode);
let userName = Auth.auth().currentUser.name
// so this is the string of the users name
I know this seems really simple and there is probably an easy way to do it that I'm not sure of. Thanks for the help!
This is how I access my firebase realtime database and read from it:
let ref = Database.database().reference()
ref.child("Username").observeSingleEvent(of: .value) {(snapshot:DataSnapshot) in
let userName = snapshot.value as? String
Print(userName)
}
Instead of where I put "Username", you can replace this with the name of the node under which the value you want to output is stored. And if this node is the child node of another, you can continue to add .child("XXX") to the line of code.
e.g.
ref.child("Account").child("Username").observeSingleEvent(of: .value) {(snapshot:DataSnapshot) in
It's tucked away a little, in providerData, which is an instance of UserInfo...
let user = Auth.auth().currentUser
let userName = user.providerData.displayName
I am trying to re-create the instagram follower and following functionality but there seems to be an error in logic. There is no error in code. What I am doing right now when the "follow" button is pressed, is to create a collection called "user-following", add the "current UID" as "document ID" and then store the following target users data as [targetuid: 1]. At the same time, I create a collection called "user-followers", add the "Target UID" as "document ID" and then store the followers data as [currentuid:1]. The issue here is that it works when it comes to following just one user. When I try to follow another, the existing following user data gets overridden with the new user whom I just followed instead of appending the data.
Example: Assume currentUser is A, user1 = B, user2 = C
When I follow user1 and user2 my database in firestore should be reflected as:
user-following -> A -> [B:1,C:1]
user-followers -> B -> [A:1]
user-followers -> C -> [A:1]
The above translates to collection -> documentID -> dictionaryvalues
The problem is that I do not get the above result. Instead when I follow user2, the value of user1 gets overridden. So there is only one dictionary value stored.
I know that the problem lies somewhere in the way I am trying to create a field under the document ID. I know I can create a dictionary and append values but I think that's a lot of code for an otherwise simple solution.
func follow(){
guard let currentUid = Auth.auth().currentUser?.uid else
{return}
guard let uid = uid else {return}
self.isFollowed = true
// Add followed user to current user-following structure
Firestore.firestore().collection("user-
following").document(currentUid).setData([uid:1])
// Add current user to followed user-follower structure
Firestore.firestore().collection("user-
followers").document(uid).setData([currentUid:1])
}
Never mind. Realised that I had to use merge.
Firestore.firestore().collection("user-
following").document(currentUid).setData([uid:1], merge: true)
This is what I want it to be
first I did it like this:
self.ref.child("User/CareGiver/\(CaregiverUID)/Followed").setValue([value2])
the result looks like in the picture. but when I add second data. It replaces the old one.
so I change to this
self.ref.child("User/CareGiver/\(CaregiverUID)").updateChildValues([
"Followed" : ["\(value2)"]])
it still replaces data at position[0] and never make it to position 1
how can I do
array [UID1,UID2,UID3] to firebase (not add array data at the same time so it would be like this)
-[0] UID1
-[1] UID2
-[2] UID3
without replacing another one?
ps.sorry for broken English
JSON should look likes this
{
"Name_Care" : "asdsāļ",
"Tel_Care" : "kknlk",
"Role" : "Care Giver",
"Followed" : [
"UID_A",
"UID_B",
"UID_C",
"UID_E"
]
}
in firebase would be like in picture
So if you want to add new values to your "followed" dictionary, you should use "setValue" function with uniq id for your new user.
Example:
self.ref.child("User/CareGiver/\(CaregiverUID)/Followed").setValue("3":"user_name")
In this case you add record user_name for key 3
I think this way can help you.
I am making a real-time messenger using Firebase. Currently, whenever I press a button I want a new message to be appended to the channel with the index of the message, but currently, whenever I press the button a new message is created that overwrites the old message. I know that setValue is usually the issue, but I really cannot tell what I'm doing wrong. What the database looks like before I add my new message. This is what it looks like after I add a new message here, and then the code I am using to add to the database.
#IBAction func sendMessageTapped(_ sender: Any) {
if messageTextField.text == "" {
print("blank")
return
} else {
// First we will update the amount of messages that the channel has.
ref.child("channels").child(channelName!).setValue(["numberOfMessages" : numberOfMessages+1 ])
numberOfMessages += 1
// after we have updated the amount of messages we will try to create a new message.
ref.child("channels").child(channelName!).child("messages").child(String(numberOfMessages)).child("message").child("content").setValue(messageTextField.text)
ref.child("channels").child(channelName!).child("messages").child(String(numberOfMessages)).child("message").child("name").setValue("Buddy")
}
}
ok, Firebase is not a traditional table based database, is a DOCUMENT based database. At the very top you have a thing called a "collection" which is just a list of "document" things. In your case, you'd have several collection things to serve as channels: "General", "TopicQ", "InterstingStuff" etc, and within them each message as a document. No need to have a document, to then list the messages within it.
Second, you don't need indexes as you're using them, make the message id an attribute of the message, because firebase support querying by field, and even then is questionable because if you make each message a document, they will have their own auto generated id's if you want.
Third, in your code you're rewriting the whole document each time, this is why you lose your previous messages, so if you keep it, you need to add a merge option:
// Update one field, creating the document if it does not exist.
db.collection("cities").document("BJ").setData([ "capital": true ], merge: true)
you probably want to do something like this. This is what I did for my app, hope this helps someone. This rootRef.childByAutoId() generates a new entry with unique id. You can use this as reference for your case.
let rootRef = Database.database().reference(withPath: "channels")
let childRef = rootRef.childByAutoId()
let values = ["Type": self.textField.text!, "message": self.textView.text!] as? [String : Any]
childRef.updateChildValues(values)
I have been looking all over the internet and Stack overflow but haven't found anything that I understood well enough to implement into my solution.
There are many similar questions out there but none of the proposed solutions worked for me, so I'll ask you guys.
How do I search my Firebase database for usernames in swift?
In my app I have a view that should allow the user to search for friends in the database. Results should be updated in real time, meaning every time the user types or deletes a character the results should update. All I have so far is a UISearchBar placed and styled with no backend code.
Since I don't really know what is needed to create such a feature it would be cool if you guys could tell me what you need to tell me exactly what to do. (Database Structure, Parts of Code...). I don't want to just copy and paste useless stuff on here.
I would really appreciate the help.
EDIT:
This is my database structure:
"users"
"uid" // Automatically generated
"goaldata"
"..." // Not important in this case
"userdata"
"username"
"email"
"country"
"..." // Some more entries not important in this case
Hope I did it right, didn't really know how to post this on here.
Suppose the Firebase structure is like this
Example 1 :
users
-> uid
->otherdata
->userdata
->username : "jen"
-> other keys
-> uid2
->otherdata
->userdata
->username : "abc"
-> other keys
And to query based on username, we need to query on queryOrdered(byChild: "userData/username"). queryStarting & queryEndingAt , fetches all the names starting from "je" and this "\uf8ff" signifies * (any) .
let strSearch = "je"
baseRef.child("users").queryOrdered(byChild: "userData/username").queryStarting(atValue: strSearch , childKey: "username").queryEnding(atValue: strSearch + "\u{f8ff}", childKey: "username").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
}) { (err) in
print(err)
}
If the username is directly below the users node, then try this
Example 2 :
users
-> uid
->username : "jen"
-> other keys
-> uid2
->username : "abc"
-> other keys
The query will be restructured as below,
let strSearch = "je"
baseRef.child("users").queryOrdered(byChild: "username").queryStarting(atValue: strSearch).queryEnding(atValue: strSearch + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
})
Please note this method is case-sensitive . The search results for search String = "je" and "Je" will be different and the query will match the case.