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.
Related
This is my firebase realtime database
Image link
This is the snippet i am using its always returning nil
let rootRef = Database.database().reference()
rootRef.child("POSTS").queryLimited(toLast: 1).observeSingleEvent(of: .value) { (myDataSnap) in
let value = myDataSnap.value as? NSDictionary
print(value as? Any)
}
If you are trying to access Id and Id's can be anything other than 0.
Than you can try the snippet below
let Key = rootRef.child("POSTS").childByAutoId().key
rootRef.child("POSTS").child(Key!).setValue(postData.toDictionary()){
(error:Error?, ref:DatabaseReference) in
if let error = error {
print("Data could not be saved: \(error).")
} else {
//do stuff
}
}
Use .childAdded or childChanged instead of .value, this might solve it
let rootRef = Database.database().reference()
rootRef.child("POSTS").queryLimited(toLast: 1).observeSingleEvent(of: .childChanged) { (myDataSnap) in
let value = myDataSnap.value as? NSDictionary
print(value as? Any)
}
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)
}
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)
}
I'm working through a course on Udemy to build a chat app with Firebase, Backendless, and Swift. All of the issues (it was written for Swift 2 not 3) I've been able to resolve myself, but this one has me stumped. This function is supposed to retrieve data from the Firebase database, and apparently it was supposed to retrieve it as an NSArray, but it now retrieves it as an NSDictionary, which is making a huge list of errors in the other functions because it's not expecting a dictionary.
func loadRecents() {
firebase.childByAppendingPath("Recent").queryOrderedByChild("userId").queryEqualToValue(currentUser.objectId).observeEventType(.Value, withBlock: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let sorted = (snapshot.value.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptior(key: "date", ascending: false)])
}
})
}
I've updated to Swift 3 as far as:
func loadRecents() {
ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let values = snapshot.value as! NSDictionary
}
})
}
Of course, using as! NSArray does not work. Would very much appreciate it if anyone can suggest a method to update this to use Swift 3, sort it by a value in the data, and be able to access it later on. Thanks!
func loadRecents() {
ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let values = snapshot.value as! [String:AnyObject]
}
})}
or you can use also let values = snapshot.value as! [Any]
Hope this will help you, try this code:
func loadRecents() {
let ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
guard let mySnapshot = snapshot.children.allObjects as? [FIRDataSnapshot] else { return }
for snap in mySnapshot {
if let userDictionary = snap.value as? [String: Any] {
print("This is userKey \(snap.key)")
print("This is userDictionary \(userDictionary)")
}
}
})
}
I'm trying to get back information from some users in Firebase.To do that, I'm running a query that selects the users based on the user's id I passed.The problem is that, inside the user object, there is another object and when I try to get the entire user in my code, I only get that last object.
This is what a user looks like in Firebase:
USERIDHERE
{
"coins" : 4850,
"name" : "Jogador 1020",
"score" : 22,
"unlocked" : {
"000" : true,
"KA0293" : true
}
}
This is the code to get the user
ref.child("users").child(key).observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children.allObjects as! [FIRDataSnapshot] {
if let dict = snap.value as? Dictionary<String,AnyObject> {
print(dict)
}
}
})
When I print the dict, instead of getting all the user information, I only get in this example the following output:
["000": 1, "KA0293": 1]
Database:
Code:
let ref = FIRDatabase.database().reference()
let refUsers = ref.child("users")
let refUser = refUsers.child("123")
refUser.observeSingleEvent(of: .value) { (snap: FIRDataSnapshot) in
if snap.exists() {
if let dict = snap.value as? [String: Any] {
print(dict)
}
}
}
Print's output:
["unlocked": {
000 = 1;
KA0293 = 1;
}, "name": Jogador 1020, "score": 22, "coins": 4850]
ref.child("users").child(key).observeSingleEvent(of: .value, with: { (snapshot) in
// you can get your user's name like below:
username = (snapshot.value as? NSDictionary)?["name"] as! String
if let dict = snapshot.value as? Dictionary<String,AnyObject> {
print(dict)
}
})
Snapshot already has user's all information.