retrieve current user data from the firebase - ios

let userId = Auth.auth().currentUser?.uid
Database.database().reference().child("Employess").child(userId!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
//print(value)
let Name = value?["name"] as? String
print(Name)
// ...
}) { (error) in
print(error.localizedDescription)
}

Related

Firebase retuns incored snapshot swift

I have a firebase chat application and I am trying to get user credentials but I am getting wrong values from the firebase in my console
that is what my ref and snapshot is and when I decide to print this in the console I get this
CREDENTiL data ref Optional({
"cc71128f-99a7-4435-879b-b1d0c7ce9c37" = {
location = "-Lav1QzhaoRMGAJHy8nQ";
};
})
CREDENTiL data ref Optional({
email = "adie.olalekan#max.ng";
name = "Olalekan Adie";
profilePicLink = "http://www.freeiconspng.com/uploads/profile-icon-9.png";
})
this is my code
self.allUserRef?.observe(.childAdded, with: { (snapshot) in
let id = snapshot.key
print("CREDENTiL data ref \(snapshot.value)")
if let data = snapshot.value as? [String: AnyObject] {
if snapshot.hasChild("credentials") {
print("CREDENTiL data \(data)")
if let credentials = data["credentials"]! as? [String: AnyObject] {
print("CREDENTiL \(credentials)")
if id != exceptID {
let userInfo = ChatUser(dictionary: data as NSDictionary)
}
}
}
}
})
Any help would be appreciated
let refer = Database.database().reference()
refer.child("chatUsers").child("your uid").observe(.childAdded, with: { (snapshot) in
let id = snapshot.value//your snapshot
if((((snapshot.value as! NSDictionary).allKeys) as! NSArray).contains("credentials"))
{
print("credentials",snapshot.value)
}
})
Please try above code to get your credentials as snapshot.

Variable username is not updated after call to Firebase

var username: String? = nil
self.ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in
let usersProfile = snapshot.value as? NSDictionary
let userProfile = usersProfile![userID] as? NSDictionary
username = userProfile!["username"] as! String
}) { (error) in
print(error.localizedDescription)
}
print(username)
Why is the variable username not updated in the end?
You can try like this
var username: String? = nil
self.ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in
if let usersProfile = snapshot.value as? NSDictionary, let userProfile = usersProfile![userID] as? NSDictionary, let name = userProfile!["username"] as? String {
username = name
}
}) { (error) in
print(error.localizedDescription)
}
print(username)

How to parse a firebase real time database

How I can parse firebase realtime database?
So far my code is:
var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("data").observe(.childAdded) { (snapshot) in
print("snapshot = \(snapshot)")
}
I can not enter the condition.
print("url = \(ref.url)")
url = "https://gdenamaz.firebaseio.com"
this variant don't work too
var ref: DatabaseReference!
ref = Database.database().reference().child("data")
ref.observeSingleEvent(of: .value) { (snapshot) in
for data in snapshot.children {
print("data = \(data)")
}
}
To reference the official docs -
refHandle = postRef.observe(DataEventType.value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
// ...
})
You want to be looking for the snapshot.value not snapshot.children
A further example
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? ""
let user = User(username: username)
// ...
}) { (error) in
print(error.localizedDescription)
}
also, .childAdded will only trigger when a child is added. IE, nothing will happen until you actually change something in that node reference.

IndexPath in cells after atomic update

I have this function that it will be triggered every time a user changes his picture, and will get the profilePictureUrl of the current user and update all posts matching the currentUser in the database. Works fine! Is doing the job. How do I update the indexPath of those particular cells? Right now my cells images are empty after the update.
var pathToPictures = [Pictures]()
func updateAllImagesOfCurrentUserInDatabase() {
//refrences
let ref = FIRDatabase.database().reference()
let uid = FIRAuth.auth()?.currentUser?.uid
//match the user ID value stored into posts with current userID and get all the posts of the user
let update = ref.child("posts").queryOrdered(byChild: "userID").queryEqual(toValue: uid)
update.observe(FIRDataEventType.value, with: { (snapshot) in
self.pathToPictures.removeAll()
if snapshot.value as? [String : AnyObject] != nil {
let results = snapshot.value as! [String : AnyObject]
for (_, value) in results {
let pathToPostPicture = Pictures()
if let pathToImage = value["pathToImage"] as? String , let postID = value["postID"] as? String {
pathToPostPicture.postImageUrl = pathToImage
pathToPostPicture.postID = postID
self.pathToPictures.append(pathToPostPicture)
print("Image and POST ID: \(pathToPostPicture.postImageUrl!)")
print("Post ID is : \(postID)")
if FIRAuth.auth()?.currentUser?.uid == uid {
ref.child("Users_Details").child(uid!).child("profileImageUrl").observeSingleEvent(of: .value, with: { (userSnapshot) in
print(userSnapshot)
let userIMageUrl = userSnapshot.value as! String
pathToPostPicture.postImageUrl = userIMageUrl
self.pathToPictures.append(pathToPostPicture)
print("This is the image path:" + userIMageUrl + String(self.pathToPictures.count))
// Update the Database
let postIDCount = pathToPostPicture.postID!
let updatedUserData = ["posts/\(postIDCount)/pathToImage": pathToPostPicture.postImageUrl!]
print("This is THE DATA:" , updatedUserData)
ref.updateChildValues(updatedUserData as Any as! [AnyHashable : Any])
})
}
print(self.pathToPictures.count)
}
}
} else {
print("snapshot is nill - add some data")
}
self.collectionView?.reloadData()
})
}

Firebase NSNull Exception while taking Snapshot of Data

i was making a Firebase practice app and i encountered this problem. Where i got NSNull exception while capturing a value from Firebase database. Here is the code
user = FIRAuth.auth()?.currentUser
ref = FIRDatabase.database().reference()
let userid = user.uid
if userid != nil
{
print("User Nid \(userid)")
ref.child("users").child(userid).observe(.value, with: {
(snapshot) in
if(snapshot.exists()){
var user_details = snapshot.childSnapshot(forPath: "\(userid)")
var user_det = user_details.value as! Dictionary<String, String>
print("User Name \(user_det["name"])")
}
else{
print("Does not exist")
}
})
}
and here is the database.
uid
user-details
name: "Salman"
propic: "picurl"
Could you try with this way
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
if let userDetail= value?["user-details"] as? [String:Any] {
// let username = value?["name"] as? String ?? ""
let username = userDetail["name"] as? String ?? ""
}
}) { (error) in
print(error.localizedDescription)
}

Resources