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

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

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 fetching ordered by value only 20 first entries

I am working on a Forum that will have an unlimited number of topics created by users. So for performance I'd like to fetch only 20 topics or so at a time. When the user goes to the bottom of the Table View we should fetch 20 more and so on.
The problem is I am currently sorting the topics AFTER I fetch all of them from Firebase and I am having a hard time having them ordered correctly directly on Firebase BEFORE I fetch them and that's the only way I can see this working.
The topics are ordered by "last-post" which is a string on Firebase that I convert to Date and reorder after I pull from Firebase.
func fetchTopicsFromFirebase(){
guard let cat = self.currentCategory else {return}
DataService.ds.Topics_Base.child(cat.key).observe(.value, with: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {//snapshots = all topics
self.allTopics = []
for top in snapshots{
if let dict = top.value as? Dictionary<String,AnyObject>{
guard let title = dict["title"] as? String else {continue}
guard let text = dict["text"] as? String else {continue}
guard let time = dict["time"] as? String else {continue}
guard let username = dict["username"] as? String else {continue}
let newTopic = Topic(subject: title, text: text, time: time, topicKey: top.key, username: username)
if let lastPost = dict["last-post"] as? String{
newTopic.lastPostTime = HelperMethods.convertStringToDate(myString: lastPost)
}
if let email = dict["email"] as? String{
let validEmail = HelperMethods.removeSpecialCharactersFromEmail(email: email)
DataService.ds.Users_Base.child(validEmail).observeSingleEvent(of: .value, with: {(snapshot) in
if let userDict = snapshot.value as? Dictionary<String,AnyObject>{
if let imgUrl = userDict["profile_image_url"] as? String{
newTopic.opImageUrl = imgUrl
}
self.allTopics.append(newTopic)
self.allTopics.sort { $0.lastPostTime! > $1.lastPostTime!}//lastPostTime is a Date object
if (self.allTopics.count == snapshots.count){
self.tableView.reloadData()
}
}
})
}
}
}
}
}
)
}
Thanks in advance for any help.

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: Access a snapshots children using swift3

I'm trying to get the value of multiple children of my snapshot in order to append my cellDataArray by name and speed.
My code is working for name, but not for speed..
ref = FIRDatabase.database().reference().child("BasicInfo")
let query = ref?.queryOrdered(byChild: "Operator")
query?.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
let name = child.key
let speed = child.childSnapshot(forPath: "Speed")
self.cellDataArray.append(cellData(mainText: name, Speed: ""))
self.tableView.reloadData()
}
})
This is my Firebase structure:
Try to access the value property of FIRDataSnapshot to get the Speed.
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
let name = child.key
if let dic = child.value as? [String:Any], let speed = dic["Speed"] as? Int
let operator = dic["Operator"] as? String {
print(operator)
self.cellDataArray.append(cellData(mainText: name, Speed: "\(speed)"))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}

Fetching Firebase Records Based on Email

I am trying to fetch all the driveways which belongs to user using their email as the search key.
And here is the code I am writing:
guard let currentUser = FIRAuth.auth()?.currentUser else {
return
}
let query = FIRDatabase.database().reference(withPath :"driveways").queryEqual(toValue: currentUser.email!, childKey: "email")
query.observe(.value, with: { (snapshot) in
print(snapshot)
})
How can I get all the driveways based on user's email address?
Try this (Swift 3 Firebase 3)
let email = "johndoe#gmail.com"
let queryRef = drivewaysRef.queryOrdered(byChild: "email")
.queryEqual(toValue: email)
queryRef.observeSingleEvent(of: .value, with: { snapshot in
for snap in snapshot.children {
let driveSnap = snap as! FIRDataSnapshot
let driveDict = driveSnap.value as! [String:AnyObject] //driveway child data
let city = driveDict["city"] as! String
let state = driveDict["state"] as! String
print("email: \(email) city: \(city) state: \(state)")
}
})

Resources