Firebase Realtime Database Connection Refresh - ios

I have two controllers one is login and another is tableView Controller where I am displaying users information.
When app starts it first checks if user is logged in or not.
If user is logged in, it will fetch users data from firebase realtime database and display in tableView. If not then it will show login controller where user have to login using email and password.
Now once i logged in i can see users data into TableViewController from firebase, But if i closed app without log out and open it after some time like 20 min later or next day when the app launch it check if user is logged in or not in my case it shows logged in and display tableViewController but it is empty it does not fetch users data from firebase realtime database.
If i will logged out and login again then i can see users data coming from firebase but if i close app and open it again after sometime it will not show any data into my tableViewController.
I dont want users to login every time in application to get firebase data if user is logged in it must show the data from firebase real time database.
Following is code to check if user is logged in or not
if Auth.auth().currentUser?.uid == nil{
print("Logout call")
perform(#selector(handleLogout), with: nil, afterDelay: 0)
}else{
print("User Logged In")
fethUserAndSetupNavbarTitle()
}
following code will get data from firebase realtime database.
guard let uid = Auth.auth().currentUser?.uid else {
return
}
let dbReference = Database.database().reference().child("Users").child(uid)
dbReference.observeSingleEvent(of: .value, with: { (snapshot)
in
if let dictionary = snapshot.value as? [String:AnyObject] {
let user = Users(dictionary: dictionary)
print("setup navbar called")
self.setupNavBarWithUser(user)
}
}, withCancel: { (error) in
print(error.localizedDescription)
return
})
Please let me know if i am unable to describe the problem.
Thank you in advance.

I might know what the problem is.
The Firebase Token gets disabled after one hour or so.
You need to enable Token Service API to allow refreshing the token once it expires.
Go to https://console.developers.google.com/ , click onto "Enable APIs And Services", search for Token Service API and enable it.

Related

firebase real time dB retrieving of specific data from multiple users in swift

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.

Firesbase authentication iOS login get user detail

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.

Swift - Firebase Authentication State Persistence

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")
}

Removing a specific value off of firebase database

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.

Delete user in iOS using Parse login

I'm implementing parse login in iOS using swift. From a login view controller i get new users to signup via swift using just email and password. This creates a PFUser which correctly saves to Parse backend. The user is then taken to a UserDetails view controller to "complete" their signup by providing more details which gets saved to coredata (im using parse functionality just for the signup). If the user cancels however before "completing" the additional details, I want to delete the PFUser from parse created possibly moments earlier. In the UserDetails view controller under cancelTapped ibaction im running code
if PFUser.currentUser() != nil {
PFUser.currentUser()?.deleteInBackgroundWithBlock({ (deleteSuccessful, error) -> Void in
print("success = \(deleteSuccessful)")
})
//user deleted in background block above but still logged in so now logout
PFUser.logOut()
}
but im getting following parse error [Error]: User cannot be deleted unless they have been authenticated. (Code: 206, Version: 1.8.5) .... i dont know what authentication process is needed and im guessing the problem could be because im trying to delete a user before parse has had a proper time to create the user in the first place .... any help or suggestions appreciated
User ALC permission automatically blocks anyone else from performing a write/delete on your record. This means you must be logged in if you want to update/delete your own record. In your code, you probably log out before your asynchronous delete code gets a chance to run in the background. Instead you need to log the user out after the delete was successful in the completion block of deleteInBackgroundWithBlock function.
if PFUser.currentUser() != nil {
PFUser.currentUser()?.deleteInBackgroundWithBlock({ (deleteSuccessful, error) -> Void in
print("success = \(deleteSuccessful)")
PFUser.logOut()
})
}

Resources