How to retrieve data from current User in Firebase using Swift? - ios

I am trying to get current users firstname from firebase using swift code. Below is my JSON file and swift code. But it's not retrieving first name. Please suggest
Json:
Swift code:
if FIRAuth.auth()?.currentUser != nil{
let queryRef = FIRDatabase.database().reference().child("expatsappmembers")
let userID : String = (FIRAuth.auth()?.currentUser?.uid)!
print("Current user ID is" + userID)
queryRef.child("uid").child(userID).observeSingleEvent(of: .value, with: {(snapshot) in
print(snapshot.value)
let userName = (snapshot.value as! NSDictionary)["firstname"] as! String
print(userName)
})
}

It is slightly different to get a value from Firebase in Swift 3
the proper way to do it is:
ref.child("expatsappmembers").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let firstName = value?["firstname"] as? String
// ...
}) { (error) in
print(error.localizedDescription)
}

Related

Firebase snapshot returns null

Hi guys I have been using firebase to write and read values from the database. It was working awesome until I wrote a function to retrieve values or products stored using swift in the following way.
Here is my code
func retrieveLiveUrlFor(product: Product){
if let path = product.prodRef{
print("Looking for : \(path)")
var liveUrl = ""
let ref = Database.database().reference(withPath: path)
ref.observe(. value, with: {
snapshot in
print("Snap : \(snapshot.value)")
if snapshot.exists(){
print("Snap : \(snapshot.value)")
let dic = snapshot.value as? NSDictionary
if dic != nil{
let url = dic?["liveUrl"] as? String
print("Url is here")
if url != nil{
print("URL is not nil")
liveUrl = url as! String
}
}
}
if (self.productdelegate != nil){
print("Calling Product delegate")
self.productdelegate?.liveUrlObtained!(liveUrl: liveUrl)
}
})
}
}
And this is the value of the path that I am trying to retrieve
Products/Live/Global/WpMvDJZUclRlfHFJsSlBEbi0jHf1
And here is the snap of the firebase database
The snapshot.value alwasy returns null in swift.
When I print using
print("Snap: \(snapshot.value)")
It prints the following
Snap : Optional()
Please guide me what I am doing wrong so that I can get to it.
If you are observing using the .value event, then a return of snapshot.value as nil means that the snapshot value does not exist at that reference. Try printing the snapshot as a whole and the snapshot.key
ideally the reference you need is
let ref = Database.database.reference().child("Products").child("Live").child("Global").child("WpMvDJZUclRlfHFJsSlBEbi0jHf1")
The observer would function like this:
ref.observe(.value) {(snapshot) in
print(snapshot.value!)
}

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

Firebase retrieve data below auto ID In Swift

I'm in trouble in retrieving data from Firebase.
I'd like to read all contactName data in JSON under auto ID , then append to UIPickerView.
Here is my JSON tree (used childByAutoId())
And Here is my Swift Code
dbRef = Database.database().reference()
dbRef.child("user").child("contacts").queryOrdered(byChild: "contactName").observeSingleEvent(of: .value, with: {(snapshot) in
for snap in snapshot.children {
let userSnap = snap as! DataSnapshot
let contactName = userSnap.value as? String
self.pickOption.append("\(contactName)")
}
})
But the result shows me all nil data... looks like this.
How Can I fix it..?
I solved myself!
But first of all, I decided not to use UIPickerView.
And what I wanna do is to add data below auto ID.
I'm not sure this is good algorithm for solving this problem, But Anyway, I made it :)
dbRef.child("user/contacts/").observe(.value, with: {(snapshot) in
if let result = snapshot.children.allObjects as? [DataSnapshot] {
for child in result {
let orderID = child.key as String //get autoID
self.dbRef.child("user/contacts/\(orderID)/contactName").observe(.value, with: { (snapshot) in
if let nameDB = snapshot.value as? String {
if self.debtorName == nameDB {
self.dbRef.child("user/contacts/\(orderID)").updateChildValues(data)
}
}
})
}
}
})

Swift Get Specific Value From Firebase Database

I'm trying to get a specific value from Firebase Database. I looked some of the documents such as Google's, but I couldn't do it. Here is the JSON file of the database:
{
"Kullanıcı" : {
"ahmetozrahat25" : {
"E-Mail" : "ahmetozrahat25#gmail.com",
"Yetki" : "user"
},
"banuozrht" : {
"E-Mail" : "banuozrahat#gmail.com",
"Yetki" : "user"
}
}
}
Swift Code:
ref?.child("Kullanıcı").child(userName.text!).observeSingleEvent(of: .value, with: { (snapshot) in
if let item = snapshot.value as? String{
self.changedName = item
}
})
I want to get E-Mail value of a user, not everybody's. How can I do that?
At last I found a solution. If I declare a var and try to use later it returns nil, but if I try use snapshot.value as? String it's ok. Here is a example I did.
ref: FIRDatabaseReference?
handle: FIRDatabaseHandle?
let user = FIRAuth.auth()?.currentUser
ref = FIRDatabase.database().reference()
handle = ref?.child("Kullanıcı").child((user?.uid)!).child("Yetki").observe(.value, with: { (snapshot) in
if let value = snapshot.value as? String{
if snapshot.value as? String == "admin"{
self.items.append("Soru Gönder")
self.self.tblView.reloadData()
}
}
})
In your code, the snapshot will contain a dictionary of child values. To access them, cast the snapshot.value as a Dictionary and then accessing the individual children is a snap (shot, lol)
ref?.child("Kullanıcı").child(userName.text!)
.observeSingleEvent(of: .value, with: { (snapshot) in
let userDict = snapshot.value as! [String: Any]
let email = userDict["E-Mail"] as! String
let yetki = userDict["Yetki"] as! String
print("email: \(email) yetki: \(yetki)")
})
Add the "E-Mail" child to the query.
ref?.child("Kullanıcı").child(userName.text!).child("E-Mail").observeSingleEvent(of: .value, with: { (snapshot) in
if let item = snapshot.value as? String{
self.changedName = item
}
})

Firebase Accessing Snapshot Value Error in Swift 3

I recently upgraded to swift 3 and have been getting an error when trying to access certain things from a snapshot observe event value.
My code:
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let username = snapshot.value!["fullName"] as! String
let homeAddress = snapshot.value!["homeAddress"] as! [Double]
let email = snapshot.value!["email"] as! String
}
The error is around the three variables stated above and states:
Type 'Any' has no subscript members
Any help would be much appreciated
I think that you probably need to cast your snapshot.value as a NSDictionary.
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let username = value?["fullName"] as? String ?? ""
let homeAddress = value?["homeAddress"] as? [Double] ?? []
let email = value?["email"] as? String ?? ""
}
You can take a look on firebase documentation: https://firebase.google.com/docs/database/ios/read-and-write
When Firebase returns data, snapshot.value is of type Any? so as you as the developer can choose to cast it to whatever data type you desire. This means that snapshot.value can be anything from a simple Int to even function types.
Since we know that Firebase Database uses a JSON-tree; pretty much key/value pairing, then you need to cast your snapshot.value to a dictionary as shown below.
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
if let firebaseDic = snapshot.value as? [String: AnyObject] // unwrap it since its an optional
{
let username = firebaseDic["fullName"] as! String
let homeAddress = firebaseDic["homeAddress"] as! [Double]
let email = firebaseDic["email"] as! String
}
else
{
print("Error retrieving FrB data") // snapshot value is nil
}
}

Resources