Firebase function in firebase function - swift

The following function has to return all of my users's friends list. However it only does it for one of the friends. I know this is because the 2 firebase functions are running async, however I am not sure what I have to change the function so that it runs the way is should. That is retrieve all friends.
///retrieves all of user's friends
func fetchFriends(completion: #escaping ([FriendModel])->()){
FRIEND_REQ_REF.child(CURRENT_USER_ID).observe(.childAdded, with: {(snapshot) in
var friends = [FriendModel]()
if snapshot.value as? Int == 0 {
self.USERS_REF.child(snapshot.key).observeSingleEvent(of: .value, with: {(snap) in
if let dictionary = snap.value as? [String : AnyObject]{
let friend = FriendModel()
friend.setValue(dictionary["userName"], forKey: "userName")
friend.setValue(dictionary["name"], forKey: "name")
friends.append(friend)
completion(friends)
}
})
}
})
}
this is my data structure:
FRIEND_REQ_REF
firebaseUserID
friendFirebasegivenID : 0
anotherFriendFirebasegivenID : 0
USERS_REF
friendFirebasegivenID
userName : String
name : String
anotherFriendFirebasegivenID : 0
userName : String
name : String

///retrieves all of user's friends
func fetchFriends(completion: #escaping ([FriendModel])->()){
FRIEND_REQ_REF.child(CURRENT_USER_ID).observe(.value, with: {(snapshot) in
var friends = [FriendModel]()
if let dict = snapshot.value as? [String : AnyObject] {
for (_,k) in dict.enumerated() {
if k.value == 0 {
self.USERS_REF.child(k.key).observeSingleEvent(of: .value, with: {(snap) in
if let dictionary = snap.value as? [String : AnyObject]{
let friend = FriendModel()
friend.setValue(dictionary["userName"], forKey: "userName")
friend.setValue(dictionary["name"], forKey: "name")
friends.append(friend)
completion(friends)
}
})
}
}
}
})
}

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.

Fetch multi level node from Firebase

I am trying to fetch the "friends" from the node to be able to show them in UICollectionView afterwards. I now realized that I have to use a struct and place the Friends array inside. I am struggling now to understand how to fetch them into that array (you can see it at the bottom of the post). Data is stored in a firebase node. How can I grab the data and what would be the procedure to place it in UICollectionView afterwards? This is my function so far to retrieve.
UPDATE: (I think I am fetching correctly now but I don't get any results. Is there something that I should do in collection view? or what am I doing wrong?)
UPDATE: Here is my code for post fetching:
func fetchPosts3() {
ref.child("Users_Posts").child("\(unique)").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in
print(snapshot)
if snapshot.value as? [String : AnyObject] != nil {
let allPosts = snapshot.value as! [String : AnyObject]
self.posts.removeAll()
for (_, value) in allPosts {
if let postID = value["postID"] as? String,
let userIDDD = value["userID"] as? String
{
//ACCESS FRIENDS
ref.child("Users_Posts").child("\(unique)").child(postID).child("friends").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snap) in
print("FRIENDS: \(snap.childrenCount)")
//var routine = self.postsWithFriends[0].friends
for friendSnap in snap.children {
if let friendSnapshot = friendSnap as? DataSnapshot {
let friendDict = friendSnapshot.value as? [String: Any]
let friendName = friendDict?["name"] as? String
let friendPostID = friendDict?["postID"] as? String
let postsToShow = PostWithFriends(id: userIDDD, friends: [Friend(friendName: friendName!, friendPostID: friendPostID!)])
self.postsWithFriends.append(postsToShow)
print("COUNTING: \(self.postsWithFriends.count)")
// then do whatever you need with your friendOnPost
}
}
})
}
}
//GET LOCATION
self.collectionView?.reloadData()
self.posts.sort(by: {$0.intervalPosts! > $1.intervalPosts!})
}
})
ref.removeAllObservers()
}
That's how the data looks at the database:
{
"-LN2rl2414KAISO_qcK_" : {
"cellID" : "2",
"city" : "Reading",
"date" : "2018-09-23 00:41:26 +0000",
"friends" : {
"UJDB35HDTIdssCtZfEsMbDDmBYw2" : {
"name" : "Natalia",
"postID" : "-LN2rl2414KAISO_qcK_",
"userID" : "UJDB35HDTIdssCtZfEsMbDDmBYw2"
},
"Vyobk7hJu5OGzOe7E1fcYTbMvVI2" : {
"name" : "Gina C",
"postID" : "-LN2rl2414KAISO_qcK_",
"userID" : "Vyobk7hJu5OGzOe7E1fcYTbMvVI2"
}
},
}
}
And this is my object that's stored into array
struct PostWithFriends {
var postID : String?
var friends: [Friend]
}
class Friend : NSObject {
var friendName: String?
var friendUserID: String?
var postID: String?
init(friendName: String, friendPostID: String) {
self.friendName = friendName
self.postID = friendPostID
}
}
Replace this
if let friend = snap.value as? [String : AnyObject] {
}
With this:
for friendSnap in snap.children {
if let friendSnapshot = friendSnap as? FIRDataSnapshot {
let friendOnPost = FriendOnPost()
let friendDict = friendSnapshot.value as? [String: Any]
friendOnPost.name = friendDict?["name"] as? String
friendOnPost.friendUserID = friendDict?["userID"] as? String
friendOnPost.postID = friendDict?["postID"] as? String
// then do whatever you need with your friendOnPost
}
}

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