I can fetch all data but don't know how to go inside the nodes
and fetch values. Here is the structure of my database want to fetch all data
func fetchData(){
ref = Database.database().reference()
let userid = Auth.auth().currentUser?.uid
ref.child(Constants.NODE_MAINTENANCE).child(userid!).child(Constants.NODE_MAINTENANCE_DATE).child(self.lastMaintenanceDateLbl.text ?? "").observe(DataEventType.value) { (snap) in
guard snap.exists()
else {
print("no data found at this date")
AppUtils.showAlert(title: "Alert", message: "No data found at this date!", viewController: self)
return}
// let maintenanceType = snapshot.value as? [String] ?? [""]
// print(maintenanceType)
if let snapshot = snap.children.allObjects as? [DataSnapshot]{
for snap in snapshot{
let maintenanceType = snap.value as? [String:Any]
for type in (maintenanceType?.values)!{
print(type)
}
}
}
}
Related
I am storing data in my firebase database but when I want to retrieve the differents name of my users, unlike my profile image who is retrieving from most recent, the names are retrieving in alphabetical orders... here's my code :
func getNamesUser(){
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "name")
query.observeSingleEvent(of: .value) { (snapshot) in
let nameArray = snapshot.children.allObjects as! [DataSnapshot]
for child in nameArray{
let value = child.value as? NSDictionary
let child = value?["name"] as? String
self.arrayName.append(child!)
}
self.collectionView.reloadData()
}
}
func getImgUser(){
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "profileImgURL")
query.observeSingleEvent(of: .value) { (snapshot) in
let nameArray = snapshot.children.allObjects as! [DataSnapshot]
for child in nameArray{
let value = child.value as? NSDictionary
let child = value?["profileImgURL"] as? String
self.arrayProfilImage.append(child!)
}
self.collectionView.reloadData()
}
}
and here's my firebase database tree :
I'm trying to extract all objects(See picture below) from Firebase Firestore. How can I add the output result into a dictionary?
func getLinks() {
let user = Auth.auth().currentUser
let userID = user?.uid
let db = Firestore.firestore()
print(userID!)
let docRef = db.collection("files").document(userID!)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
}
Output Image
Fetch Data from Firebase and then Use it
Step:-1 Fetch Data
var dictData = [String:Any]()
let ref = Database.database().reference()
ref.observe(.childAdded, with: { (snapshot) in
print(snapshot.value!)
self.dictData = snapshot.value as! [String : Any]
print(self.dictData)
})
Step:- 2 Extract the Data from SnapShot
var arrFetchedData:NSMutableArray = NSMutableArray()
for data in dictData{
print(data.key) //Key will be printed here
var tempDict:NSMutableDictionary = NSMutableDictionary()
let innerData = data.value as! [String:Any]
let expires = innerData["expires"]
tempDict.setValue(expires, forKey: "expires")
let name = innerData["name"]
tempDict.setValue(name, forKey: "name")
let url = innerData["url"]
tempDict.setValue(url, forKey: "url")
arrFetchedData.add(tempDict)
}
print(arrFetchedData) //All the Fetched data will be here
Hope this Helps!
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
}
})
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)
}
My code is kind of buggy lately and I wonder if the methods I am using to retrieve data from Firebase are the correct methods to use. In short, I am retrieving data from firebase and than storing it inside an SQLite database.
This is my code:
FirebaseStore.rootRef.childByAppendingPath("users/"+FirebaseStore.rootRef.authData.uid+"/forums").observeSingleEventOfType(.Value, withBlock:{
snapshot in
guard let firebaseData = snapshot.value as? NSDictionary else {return}
guard let uids = firebaseData.allKeys as? [String] else {return}
importContext.performBlock{
for uid in uids{
guard let forum = NSEntityDescription.insertNewObjectForEntityForName("Forum", inManagedObjectContext: importContext) as? Forum else {return}
FirebaseStore.rootRef.childByAppendingPath("forums/"+uid+"/posts").queryOrderedByKey().observeSingleEventOfType(.Value, withBlock: {
snapshot in
// Saving the chat's messages
guard let data = snapshot.value as? NSDictionary else {return}
importContext.performBlock{
guard let posts = NSEntityDescription.insertNewObjectForEntityForName("Post", inManagedObjectContext: importContext) as? Post else {return}
do{
try importContext.save()
}catch let error{
// Error
}
}
})
}
}
})
}
I am not sure if I have to call this observeSingleEventOfType.