I am setting up a social media app and currently working on a way to create authentic usernames(no duplicates) for the user to enter, similar to that of Instagram.
The problem that I'm facing is that I can't find a way to delete the users previous username(in case anyone else wants to use it). The way that my database is setup for usernames is like:
Usernames
- username:"testUsername"
I have attempted to delete the code using this
let usernameRef = FIRDatabase.database().reference().child("Usernames").child("username").child(usersCurrentUsername)
usernameRef.removeValue(completionBlock: {(error, ref) in
if error != nil {
print("There was an error in removing the current username\(error?.localizedDescription)")
} else {
print(ref)
print("The child was removed")
}
})
I capture the users current username via snapshot in the viewdidload and store it in usersCurrentUsername.
Any help would be appreciated
let usernameRef = FIRDatabase.database().reference().child("Usernames").child("username");
usernameRef.removeValue();
Note that if the child of Usernames is only the username, the Usernames node will also be deleted.
Related
so I'm working these days on a new project and I have a problem I can't solve, I hope someone can help me.
I'm working on an iOS app, I'm storing all user data on Firebase Real time dB.
My main goal is to get specific data from all users from particular positions,
For example:
Inside users, I have different UIDs of all the users in the dB.
In each one of them, there is a username, I would like to retrieve the username of each user.
In the future, I would like to store the location for each user under "Location". and then I would like to get all users that their location is "New-York".
I'll be glad to get some ideas on how to figure it out!
Thanks!
users
XLS37UqjasdfkKiB
username: "Donald"
ei8d4eYDafjQXyZ
username: "Barak"
etcj0lbSX5Oasfj
username: "Abdul"
rglmlG6Rasdgk5j
username: "Ron"
You can:
Load all JSON from /Users.
Loop over snapshot.children.
Then get the value of each child's username property.
These are also the most common navigation tactics when it comes to Firebase Realtime Database, so you'll apply these to pretty much any read operation.
Something like this:
Database.database().reference().child("isers").observe(.value, with: { (snapshot) in
if !snapshot.exists() {
print("No users found")
} else {
for case let userSnapshot as DataSnapshot in snapshot.children {
guard let dict = userSnapshot.value as? [String:Any] else {
print("Error")
return
}
let username = dict["username"] as? String
print(username)
}
}
})
Also see:
the documentation on reading data.
the documentation on listening for lists of data with a value event.
How to properly use queryOrderedByValue
Get Children of Children in Firebase Using Swift
And more from searching on [firebase-realtime-database][swift] children.
in my application the user can sign up and by doing that I also save the firstname, lastname and uid.
This is how Firestore-Database looks like:
I would like to access the users lastname but I do not know how, as the Document-ID gets created randomly in the sign-up process.
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
//check for errors
if let err = err {
self.view.endEditing(true)
self.showError(err.localizedDescription)
}else {
//user was created successfully; store first and last name
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["firstname":firstName, "lastname": lastName, "uid": result!.user.uid]) { (error) in
if error != nil {
self.showError("Error saving user data")
}
}
//transition to home
self.transitionToHome()
}
You need to know one of two things in order to get a document in Firestore:
The full path of the document, including the name of the collection and ID of the document (and any nested subcollections and document IDs)
Something about the data in that document, for example, a value of one of its fields.
If you don't know either of these things, then all you can do is fetch all the documents in a collection and try to figure out what you want by looking at everything in the collection.
The bottom line is that if you don't know which document belongs with which user, you are kind of stuck. You should store the ID of the user in the document, or as the ID of the document itself, so that you can use it to find that document later.
I suggest using the Firebase Auth user ID as the ID of the document. This is extremely common. Don't use addDocument to write it with a random ID, use setData with the ID you know.
Firestore cannot just know which document you want at any time, unless you provide a way for it to locate the document.
I have just followed and correctly added the following tutorial to my app. But I’m struggling on how to get the ‘logged in’ users details from the Firestore database?
The Tutorial:
https://youtu.be/1HN7usMROt8
Once the user registers through my app the ‘First name’, ‘last name’ and ‘UID’ are saved by the Firestore database. But once the user logs in how do I GET the users first name to copy to a label on a welcome screen inside the app?
Thanks
I suppose that you know how Firestore works. If you don't you can get all informations in this documentation or watch videos about Firestore on YouTube.
So let's say you have your users saved in collection named users. When the user sign in you can get current user like this:
let currentSignInUser = Auth.auth().currentUser!
If you will force unwrap it make sure that user will be signed in.
When you have current user you can get his uid by calling uid property of current user:
let currentUserID = currentSignInUser.uid
Now you can query this uid to get documents from Firestore users collection that have same UID field value as your current signed in user:
let query = Firestore.firestore().collection("users").whereField("UID", isEqualTo: currentUserID)
Make sure that the first parameter of whereField() function is same as your field name in documents. Because you mention that UID is saved to database I name it UID.
This is all for getting informations of your current user and making query out of it. Now you can GET documents from Firestore:
query.getDocuments() { [weak self] (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
if let userInfo = querySnapshot?.documents.first {
DispatchQueue.main.async {
// Set label text to first name
self?.youLabel.text = userInfo["firstName"]
}
}
}
}
Change userInfo key to whatever name have you used for storing first name in Firestore. For example if you named your document field firstName then userInfo dictionary key must be firstName.
I'm currently thinking about implementing Firebase Auth to my Swift project, hence I've been reading some articles. - Namely among others this one.
I need some help understanding the given article. It's about "Authentication State Persistence". Does this mean, that if the value is set to local, the user will stay logged in even after closing the app? In other words, will he be able to sign up once and stay logged in until he decides to log out - even when he's offline?
Let's say a user decides not to create an account and logs in with "Anonymous Authentication" (I assume this is the type of login in this kind of case) - will he stay logged in forever as well or is there a danger of data loss, in case of going offline or closing the app?
First: the link you provided refers to a javascript firebase documentation
Second: the only thing available in IOS is you can create an anonymous user with
Auth.auth().signInAnonymously() { (authResult, error) in
// ...
let user = authResult.user
let isAnonymous = user.isAnonymous // true
let uid = user.uid
}
and you can convert it to a permanent user check This
Finally: whether the user is usual / anonymous , after you sign in you need to check this to show login/home screen every app open
if FIRAuth.auth()?.currentUser != nil {
print("user exists")
}
else {
print("No user")
}
and the user still exists unless you sign out regardless of whether you closed the app or not
If you are using the latest Firebase version, FIRAuth is now Auth:
if Auth.auth()?.currentUser != nil {
print("user exists")
}
else {
print("No user")
}
I'm having a bit of trouble adding users to Firebase. If anyone could help me out with this, it would be significantly appreciated.
Here is my code:
var myRootRef = Firebase(url:"https://plattrapp.firebaseio.com/users")
myRootRef.createUser(emailSignUpEntered, password: passwordSignUpEntered,
withValueCompletionBlock: { error, result in
if error != nil {
// There was an error creating the account
} else {
let uid = result["uid"] as? String
println("Successfully created user account with uid: \(uid)")
}
})
It does display in the println statement within my debugger that a user has been created, but doesn't actually display within my firebase database.
Anything I may be doing wrong?
Firebase Authentication does not automatically create any information about the user in the associated database.
Most applications end up creating this information from their own code under a top-level users node. This is covered in the section called "Storing User Data" in the Firebase programming guide for iOS.
It is in general a good idea to read the Firebase documentation on the topic that you are working on. It will prevent a lot of grey/lost hair and wasted time.