Firebase data into an Array of dictionaries. iOS, Swift - swift

I'm trying to retrieve data from a firebase database and store the result in an array of dictionaries. I want to store the data in this way....
[[postcode: postcode, latitude: 87.28764862, longitude: -23.94679475694, registration: registration], [postcode: postcode, latitude: 87.28764862, longitude: -23.94679475694, registration: registration], [postcode: postcode, latitude: 87.28764862, longitude: -23.94679475694, registration: registration]]
The result I'm getting is...
Tony: before append post []
Tony: post [appname.Post]
Where am I going wrong?
var places = [String]()
var postsNew = [Post]()
var posts = [String: Any]()
DataService.ds.REF_POSTS.observe(.value, with: { (snapshot) in
if snapshot.hasChild("postCodes") {
let refToUser = DataService.ds.REF_POSTS
refToUser.child("postCodes").observe(.value, with: { snapshot in
let value = snapshot.value as? NSDictionary
let postsIds = value?.allKeys as! [String]
for postId in postsIds {
let refToPost = Database.database().reference(withPath: "posts/" + "postCodes/" + postId)
refToPost.observe(.value, with: { snapshot in
if snapshot.exists() {
let postDict = snapshot.value as? Dictionary<String, AnyObject>
let pCodeData = snapshot.key
let post = Post(postKey: pCodeData, postData: postDict!)
self.configureCell(post: post)
print("Tony: before append post \(self.postsNew)")
self.postsNew.append(post)
print("Tony: post \(self.postsNew)")
}else {
print("Tony: Couldn't get the data")
}
})
}
})
}else {
print("Tony: No Favs added, couldn't get the data")
}
})
func configureCell(post: Post) {
self.postData = post
self.latitude = post.latitude
self.longitude = post.longitude
self.postCodeDB = post.postCode
self.registration = post.other2
}
and in my Post class..
init(postKey: String, postData: Dictionary<String, AnyObject>) {
self._postKey = postKey
my firebase data...
If I add another one to my firebase I get this result...

I found the answer by reviewing my code.
DataService.ds.REF_POSTS.child("postCodes").observe(.value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let postsIds = value?.allKeys as! [String]
for postId in postsIds {
let refToPost = Database.database().reference(withPath: "posts/" + "postCodes/" + postId)
refToPost.observe(.value, with: { snapshot in
if snapshot.exists() {
let postDict = snapshot.value as? [String: AnyObject]
print("Tony: before append post \(self.posts)")
self.posts.append(postDict!)
print("Tony: post \(self.posts)")
self.showSightingsOnMap()
}else {
print("Tony: Couldn't get the data")
}
})
}
})

Related

Cant fetch from Firebase Realtime Database

I don't know why cant find how get friends Ids.
her is my code:
func fetchUsers() {
let ref = Firebase.Database.database().reference()
guard let userId = Auth.auth().currentUser?.uid else { return }
let userID = userId
ref.child("Users").child(userID).observe(.childAdded) { (snapshot) in
print("snapshot...\(snapshot)")
let user = User()
if let dictionary = snapshot.value as? [String:AnyObject]{
user.currentUserFriends = dictionary["Friends"] as? String
print("dictionary...\(user.currentUserFriends ?? "no value")")
}
}
}
and my tree from firebase is Users-Uid-Friends-friendID-true.
Solved!
ref.child("Users").child(userID!).child("Friends").observeSingleEvent(of: .value) { (snapshot) in
print("snapshot...\(snapshot)")
let dic = snapshot.value as! NSDictionary
for (key,value) in dic{
let friendsID = key
let friendBool = value
print("key is \(friendsID) and value is \(friendBool)")
let user = User()
user.currentUserFriends = key as? String
}
}

Unable to retrieve data from Firebase Database. ref.child("").queryOrderedByKey().observeSingleEvent being unresponsive

I am trying to retrieve a list of posts from my firebase database, but it is not working. The specific piece of code that I am having trouble with is the line ref.child("users").queryOrderedByKey().observeSingleEvent. When I debug the application, it just skips over this line and the app jumps to ref.removeAllObservers(). Am I calling the correct functions to retrieve from my database? The tutorial I am using is from Swift3 so it may be outdated.
I have tried calling observe instead of observeSingleEvent, but that had the same outcome.
Here is my fetchPosts function:
func fetchPosts(){
let ref = Database.database().reference()
ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: {snapshot in
let users = snapshot.value as! [String : AnyObject]
for (_,value) in users {
if let uid = value["uid"] as? String{
if uid == Auth.auth().currentUser?.uid {
if let followingUsers = value["following"] as? [String: String]{
for(_, user) in followingUsers {
self.following.append(user)
}
}
self.following.append(Auth.auth().currentUser!.uid)
ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: {(snap) in
let postsSnap = snap.value as! [String : AnyObject]
for(_, post) in postsSnap {
if let userID = post["userID"] as? String{
for each in self.following{
if each == userID{
let posst = Post()
if let author = post["author"] as? String, let likes = post["likes"] as? Int, let pathToImage = post["pathToImage"] as? String, let postID = post["postID"] as? String{
posst.author = author
posst.likes = likes
posst.pathToImage = pathToImage
posst.postID = postID
posst.userID = userID
self.posts.append(posst)
}
}
}
self.collectionview.reloadData()
}
}
})
}
}
}
})
ref.removeAllObservers()
}
I hope to fill a collection view with post information from my Firebase database. There are no error messages.

swift snapshot firebase; which child it came from

I need a pretty simple thing and I cant figure it out. I created a snapshot of firebase, and i matched the userID with the snapshots name of inside a child. I just need the childs ID (which i created using childbyautoID)
here is my code:
func checkIfUserIsLoggedIn(){
if Auth.auth().currentUser?.uid == nil {
} else {
let uid = Auth.auth().currentUser?.uid
Database.database().reference().child("Users").child(uid!).child("data").observeSingleEvent(of: .value, with: {(snapshot) in
if let dictionary = snapshot.value as? [String:AnyObject] {
self.fnamefinal = dictionary["email"] as? String
if self.fnamefinal != nil {
self.ref.child("Request").observe(.childAdded, with: { (snapshot) in
let results = snapshot.value as? [String : AnyObject]
let name = results?["name"]
let garage = results?["garage"]
let time = results?["time"]
let latitude = results?["latitude"]
let longitude = results?["longitude"]
let childID = results?[""]
print(snapshot)
print(childID as! String?)
if name as! String? == self.fnamefinal {
let myCalls = RidesRequestedd(name: name as! String?, garage: garage as! String?, time: time as! String?, latitude: latitude as! Double?, longitude: longitude as! Double?)
self.frequests1.append(myCalls)
self.rideslabel.text = myCalls.garage
} else {
}
})
} else {
print("no")
}
}
})
//}
}
Here is the snapshot of the matched name with user ID:
Snap (-LMBAF69-kYKnWoK2n9M) {
garage = "Coliseum/Bobcat Stadium";
latitude = "29.89";
longitude = "-97.953";
name = "test3#gmail.com";
time = "12:13 AM";
}
I just need the LMBAF69.... string. Simple but i cant figure it out

Can't get node of firebase children

Hi there i'm newest in swift. I am working with a firebase database with at 2 layer of hierarchy as well as many children for each node. I got 1st layer (descript, enddata and other), but i stll can't get the news node. Is in 3 to 5 random keys. I sow many issues but still not have issue for me.
I'm understand i'm doing some wrong but what?
The Firebase is:
i need retreat the news child
struct is
struct ICONews {
let ICOId: String
let news1: String
let news2: String
let news3: String
init?(ICOId: String, dict: [String: Any] ) {
self.ICOId=ICOId
guard let news1 = dict[""] as? String,
let news2 = dict[""] as? String,
let news3 = dict[""] as? String
else { return nil }
self.news1 = news1
self.news2 = news2
self.news3 = news3
}
}
struct NewsSnapShot {
let posts: [ICONews]
init?(with snapshot: DataSnapshot) {
var posts = [ICONews] ()
guard let snapDict = snapshot.value as? [String: [String: Any]] else { return nil }
for snap in snapDict {
guard let post = ICONews (ICOId: snap.key, dict: snap.value) else {continue}
posts.append(post)
}
self.posts=posts
}
}
class of DataBase
class DatabaseService {
static let shared = DatabaseService()
private init(){}
let ICOReference = Database.database().reference()
}
and retreat method
DatabaseService.shared.ICOReference.child("news").observe(DataEventType.value, with: { (snapshot) in
guard let postsSnapShot = ICOSnapShot(with: snapshot) else {return}
})
done
Database.database().reference().observeSingleEvent(of: .value, with: {(snapshot) in
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? DataSnapshot {
let values = (rest as! DataSnapshot).value as? NSDictionary
let enumeratorMap1 = (rest as! DataSnapshot).children
while let rest2 = enumeratorMap1.nextObject() as? DataSnapshot {
let valuesMap1 = (rest2 as! DataSnapshot).value as? NSDictionary
if (rest2 as! DataSnapshot).key == "news" {
print(rest2.value)
}
}
}
})
Make the the Firebase Api call like
Database.database().reference().child("users").child(userID).observe(.childAdded, with: { (snapshot) in
if snapshot.exists() {
let receivedMessage = snapshot.value as! [String: Any]
let name = receivedMessage["name"] as? String ?? ""
let id = receivedMessage["id"] as? Double ?? 0.0
let profileurl = receivedMessage["url"] as? String ?? ""
completion(User(name: name, id: id, url: url))
} else {
failure()
}
})

How to read data from firebase

This is my realtime database structure. I have only 1 item in club. In reality, I have many items.
I want to read all clubs information, and try to get the related address using club's key.
here is my code:
func loadClubs() {
ref = Database.database().reference()
let clubRef = ref.child("club")
let refHandle = clubRef.observe(DataEventType.value, with: { (snapshot) in
if let c = snapshot.value as? [String : AnyObject] {
let name = c["name"] as! String // PRINT NIL
}
// ...
})
}
How can I retrieve a club's name, courtNum, explanation,...?
try this:-
ref = Database.database().reference()
ref.child("club").observe(.value, with: { (snapshot) in
print("clubs: \(snapshot)")
if(snapshot.exists()) {
let array:NSArray = snapshot.children.allObjects as NSArray
for obj in array {
let snapshot:FIRDataSnapshot = obj as! FIRDataSnapshot
if let childSnapshot = snapshot.value as? [String : AnyObject]
{
if let clubName = childSnapshot["name"] as? String {
print(clubName)
}
}
}
}
}