Firebase NSNull Exception while taking Snapshot of Data - ios

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

Related

Add all usernames except current user's username to array

I'm working on a follow friends view controller that loads all the usernames in the database, BUT I don't want it to load the current user's username. I need to access the username from the currentUser's uid, and add all the usernames that are not equal to it to my array.
#objc func loadData() {
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "username")
query.observeSingleEvent(of: .value) {
(snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value = child.value as? NSDictionary
let username = value?["username"] as? String ?? ""
if username != rootRef.child(Auth.auth().currentUser!.uid).value(forKey: "username") as! String{
self.usernames.append(username)
}
print(username)
}
self.tableView.reloadData()
print(self.usernames)
}
}
You should try and minimise queries inside loops, especially irrelevent ones. Given your database schema uses the users unique id as the key, you can run your evaluation based on that key using child.key.
#objc func loadData() {
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "username")
query.observeSingleEvent(of: .value) { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value = child.value as? NSDictionary
let username = value?["username"] as? String ?? ""
if Auth.auth().currentUser!.uid != child.key {
self.usernames.append(username)
}
print(username)
}
self.tableView.reloadData()
print(self.usernames)
}
}

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)

swift 3 firebase snapshot if value equal to ... fetch

I'm Trying to check if the rooms's value 'Owner' equals to the current user id if so then fetch all data including the key value and continue checking other children of 'rooms'
I was trying, but I fail finding the solution though it might seem easy so please help me with your suggestions or ideas. My code so far :
Database.database().reference().child("rooms").queryOrdered(byChild: "Owner").observeSingleEvent(of: .value, with: { (snapshot) in
let currentUser = Auth.auth().currentUser?.uid
if !snapshot.exists() {
print("No data found")
return
}
var rooms = snapshot.value as! [String:AnyObject]
let roomKeys = Array(rooms.keys)
for roomKey in roomKeys {
guard
let value = rooms[roomKey] as? [String:AnyObject]
else
{
continue
}
let title = value["title"] as? String
let description = value["description"] as? String
let roomPictureUrl = value["Room Picture"] as? String
let longitude = value["Longtitude"] as? String
let latitude = value["Latitude"] as? String
let dateFrom = value["Date From"] as? String
let dateTo = value["Date To"] as? String
let owner = value["Owner"] as? String
let myRooms = Room(roomID: roomKey,title: title!, description: description!, roomPicutreURL: roomPictureUrl!, longitude: longitude!, latitude: latitude!, dateFrom: dateFrom!, dateTo: dateTo!, owner: owner!)
self.rooms.append(myRooms)
self.tableView.reloadData()
print(snapshot.value)
}
})
You're missing the value in your query:
Database.database().reference()
.child("rooms")
.queryOrdered(byChild: "Owner")
.queryEqual(toValue: "STbz...")
.observeSingleEvent(of: .value, with: { (snapshot) in
See for this and more query operators, the documentation on filtering data.
Mark:- Swift 5
Database.database().reference().child("user")
.queryOrdered(byChild: "UserPhoneNumber") //in which column you want to find
.queryEqual(toValue: "Your phone number or any column value")
.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.childrenCount > 0
{
if let snapShot = snapshot.children.allObjects as? [DataSnapshot] {
//MARK:- User Exist in database
for snap in snapShot{
//MARK:- User auto id for exist user
print(snap.key)
break
}
}
}
else if snapshot.childrenCount == 0
{
//MARK:- User not exist no data found
}
})

retrieve current user data from the firebase

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

Resources