Retrieving data from database and displaying? IOS - ios

I'm new in Firebase and the Pods. I'm having trouble retrieving data from the Database. I think I'm doing something wrong with the libraries that Firebase has. My app runs good but doesn't show the results in the console, can someone explain why is not getting the information from my database. As well any resource from a different server will help a lot. Here is what I have.
PS: Any other information let me know Thank you!!

As first you should change your observer DateType to .value, because the .childAdded will only be executed when a child is added.
Second you should loop through all your 'bestBuyLocations?' and fetch the lat and lons.
see example below:
let databaseRef = Database.database().reference().child("bestBuy")
databaseRef.observe(.value) { snapshot in
if let snapShotValue = snapshot.value as? NSDictionary {
for location in snapShotValue {
if let locationValues = location.value as? [String: Any] {
if let lon = locationValues["lon"] as? NSString {
print(lon)
}
if let lat = locationValues["lat"] as? NSString {
print(lat)
}
}
}
}
}

As per your attached image it is firestore not realtime database. The code you have added is for real-time database. please check firestore documentation to retrieve data.

Related

Retrieving data from firebase Realtime Datbase with SwiftUI Xcode 11

For a few days I have been trying to read my data from firebase without success.
Indeed it is a set of tables also containing tables.
This function is to retrieve the subjects and at the same time the paragraphs
func getSubjects() {
let subjectRef = database.child("subjects")
subjectRef.observe(.childAdded, with: { (snapshot) in
for child in snapshot.children {
print(snapshot)
if let snapshot = child as? DataSnapshot,
let subject = Subject(snapshot.value)
//subjectList.append(subject)
// print("Data : \(subject)")
}
})
}
This is the firebase screen
Console screen
On Android I didn't have this problem, but since I'm new to iOS, I'm having a hard time coping.
Any help will be welcome. Thank you
At the moment, you are observing the database for constant changes and it will only run when a child/value has been added into the place you're currently checking, for this you may only want to retrieve a value once, and every time that view is loaded then it will fetch from the database again. It's a lot more efficient and less costly. You may want something like this:
ref = Database.database().reference()
ref.child("subjects").child("0").child("paragraphs").child("0").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let location = value["location"] as? NSDictionary
let title= value?["title"] as? String ?? ""
let text = value?["text"] as? String ?? ""
let latitude = location?["latitude"] as? String ?? ""
let longitude = location?["longitude "] as? String ?? ""
}) { (error) in
print(error.localizedDescription)
}
You think each child with nodes inside it as an array, or a json object. You can cast them into an NSDictionary and use that cast to access values inside them if they're nested.
If they're not nested and in the same level as the place you're watching in the database ref, like for instance, above we are looking in the subjects > 0 > paragraphs > 0 node within the database. Title is a value inside that node and not a child so we can simply get the value of title from the database through the data snapshot given back.
I recommend reading the Docs, they're very good and easy to understand when working with different OS/languages.

best way to handle coordinates of multiple people / objects and store that data swift

I'll start off by saying I'm very new to this and I'm having a hard time figuring out how to solve this problem. I'm trying to implement a feature like find my friends through firebase where the location of multiple people is uploaded to my firebase which then pushes the data to all the users in the group. The problem I'm having is figuring out the best way to store those locations and update them as they come in.
Here's a picture of my firebase structure but I can easily change it if I need to. The children of "locations" are the UID and when new locations become available firebase updates the child instead of making a new one
and here's my code where I was trying to save the info to a plist but I'm not married to that idea. nothing would crash when I called the saveLocations func but I wouldn't get anything in my plist either don't need the data to persist so I was thinking about using an array. I would even parse a json but then it wouldn't be location updates as they are uploaded to the sever (at least at my level of understanding)
func saveLocations(value: [LocationFormat]) {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentDirectory = paths.object(at: 0) as! String
let path = documentDirectory.appending("FriendsLocations")
let dict : NSMutableDictionary = [:]
dict.write(toFile: path, atomically: false)
print("Saved to plist")
}
func retrieveLocations() {
let retrieveMessageDB = Database.database().reference().child("\(Session.ID)").child("locations")
retrieveMessageDB.observe(.childChanged, with: { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
let lat = snapshotValue["Lat"]!
let lon = snapshotValue["Lon"]!
let name = snapshotValue["Name"]
let locationData = LocationFormat()
locationData.lat = lat
locationData.lon = lon
if name != nil {
locationData.name = name!
}
self.locationArray.append(locationData)
self.saveLocations(value: self.locationArray)
})
}

Firebase query in iOS swift

This is my first screenshot database in firebase:
This is my second screenshot database in firebase:
I am able to retrieve data from firebase also set in table view. But I want all data that which first screenshot database key (1album) equal to second database post_key: 1album.
I tried like this:
refhandel = ref.child("SongPlay").child("1album"] ).queryOrdered(byChild:"post_key").observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? [String: AnyObject]{
let music = MusicDataModel()
music.setValuesForKeys(item)
MusicData.append(music)
}
})
after read firebase documentation, I got my Answer where i made mistake.
here what i was done. i just replace queryEqual instance of child
refhandel = ref.child("SongPlay").queryOrdered(byChild:"post_key").queryEqual(toValue: post_key[myIndex]).observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? [String: AnyObject]{
let music = MusicDataModel()
music.setValuesForKeys(item)
MusicData.append(music)
}
})

how to receive / update data when it changes (Firebase) in swift

I have some data stored on firebase and when somebody adds to my data, through my app I want to receive and update my data. I looked at the google docs and it said to something like this...
databaseRef.child("Leaderboard").queryOrderedByKey().observe(.childChanged, with: {
snapshot in
let value = snapshot.value as? NSDictionary
// put data into variables
let playerName = value?["playerName"] as! String?
}
But for some reason it returns nil, I know I have my hierarchy right. Why is it returning nil?
let playerName: String = value!["playerName"] as? String

How to retrieve objects from firebase by key value

I'm new to firebase and I have such structure of my firebase project
I want to get all objects, that "Interested" value is equal to "men"
I wrote such code, to get all object sorted by interes value:
let thisUserRef = URL_BASE.childByAppendingPath("profile")
thisUserRef.queryOrderedByChild("Interest")
.observeEventType(.Value, withBlock: { snapshot in
if let UserInterest = snapshot.value!["Interest"] as? String {
print (snapshot.key)
}
}
But I receive nil.
you need to loop through all the key-value profiles
if let allProfiles = snapshot.value as? [String:AnyObject] {
for (_,profile) in allProfiles {
print(profile);
let userInterest = profile["Interest"]
}
}
Here _ is the key that is in the format KYXA-random string and profile will be the element for that key.
Edit:
There is querying for child values as per the docs.
Try thisUserRef.queryOrderedByChild("Interest").equalTo("men") and then using the inner loop that i specified in the answer
This is a basic query in Firebase. (Updated for Swift 3, Firebase 4)
let profileRef = self.ref.child("profile")
profileRef.queryOrdered(byChild: "Interest").queryEqual(toValue: "men")
profileRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let dict = child as! [String: Any]
let name = dict["Name"] as! String
print(name)
}
})
The legacy documentation from Firebase really outlines how to work with queries: find it here
Legacy Firebase Queries
The new documentation is pretty thin.
Oh, just to point out the variable; thisUserNode should probably be profileRef as that's what you are actually query'ing.

Resources