Fetch posts from postId firebase & swift - swift

I want to fetch the specific posts by they're postId. Is this something that is possible to do with firebase and swift?
Currently I'm getting a key from geofire which has all the postId keys that I want in it. Is it possible to get the post data relating to these postIds Here is my current attempt. My current attempt doesn't append any of the posts to my collectionView
var posts = [Post]()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0] as CLLocation
let currentUserLocation = userLocation
let circleQuery = geoFire?.query(at: currentUserLocation, withRadius: 100.0)
guard let uid = Auth.auth().currentUser?.uid else { return }
_ = circleQuery?.observe(.keyEntered, with: { (key, location) in
print(key)
let ref = Database.database().reference().child("posts")
var postId = key
ref.child(uid).child(postId).observe(.value, with: { (snapshot) in
self.collectionView?.refreshControl?.endRefreshing()
guard let dictionaries = snapshot.value as? [String: Any] else { return }
dictionaries.forEach({ (key, value) in
guard let dictionary = value as? [String: Any] else { return }
guard let user = Auth.auth().currentUser?.uid as? User else { return }
var post = Post(user: user, dictionary: dictionary)
post.id = key
self.posts.append(post)
self.posts.sort(by: { (post1, post2) -> Bool in
return post1.creationDate.compare(post2.creationDate) == .orderedDescending
})
})
}, withCancel: { (error) in
print("There was an error getting the posts:", error)
})
self.locationManager.stopUpdatingLocation()
})
}

use snapshot haschild to check
let ref = Database.database().reference().child("posts")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild("\(self.yourValueToCompare!)"){
print("Exists in Database")
}else{
print("Does not Exists in Database")
}
})

Related

Swift - Remove key and values from dictionary [String : Any]

I am trying to removed block users from a dictionary [String : Any] that I am grabbing from the database. At first I grab the list of UID's that the current user has blocked:
var updatedBlockList: Any?
func findBlockUsers() {
// find current users list of blocked users
guard let currentUserUid = Auth.auth().currentUser?.uid else { return }
let blockedUsers = Database.database().reference().child("users").child(currentUserUid)
blockedUsers.observeSingleEvent(of: .value, with: { (snapshot) in
guard let userIdsDictionary = snapshot.value as? [String: Any] else { return }
userIdsDictionary.forEach({ (key, value) in
guard let userDictionary = value as? [String: Any] else { return }
var blockedList : Any
blockedList = userDictionary.keys
print(blockedList)
self.updateBlockList(blockedList: blockedList)
})
})
}
func updateBlockList(blockedList: Any) {
updatedBlockList = blockedList
print(updatedBlockList)
}
If I print updatedBlockList I get: ["gdqzOXPWaiaTn93YMJBEv51UUUn1", "RPwVj59w8pRFLf55VZ6LGX6G2ek2", "xmigo8CPzhNLlXN4oTHMpGo7f213"]
I now want to take those UID's (which will be the key in UserIdsDictionary and remove them after I pull ALL the users:
fileprivate func fetchAllUserIds() {
let ref = Database.database().reference().child("users")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let userIdsDictionary = snapshot.value as? [String: Any] else { return }
userIdsDictionary.forEach({ (key, value) in
// attempting to remove the blocked users here without any luck
var updatedKey = key as String?
updatedKey?.remove(at: self.updatedBlockList as! String.Index)
print(updatedKey!)
guard let userDictionary = value as? [String: Any] else { return }
let user = User(uid: key, dictionary: userDictionary)
self.fetchPostsWithUser(user: user)
})
}) { (err) in
print("Failed to fetch following user ids:", err)
}
}
I get this error when trying to remove: Could not cast value of type 'Swift.Dictionary.Keys' (0x1de2f6b78) to 'Swift.String.Index'
I'm sure i'm going about this the wrong way, but I know i'm close. The end goal is to take the blocked users UID's and remove them from the dictionary. Any help would be very much appreciated!!
Your forEach loop on userIdsDictionary is the wrong approach here so rather than trying to fix that code I would use a different approach and loop over the updatedBlockList
for item in updatedBlockList {
if let userID = item as? String {
userIdsDictionary.removeValue(forKey: userID)
}
}
For anyone wondering, here is the final changes that were made to make it work.
var updatedBlockList = [String]()
func findBlockUsers() {
// find current users list of blocked users
guard let currentUserUid = Auth.auth().currentUser?.uid else { return }
let blockedUsers = Database.database().reference().child("users").child(currentUserUid)
blockedUsers.observeSingleEvent(of: .value, with: { (snapshot) in
guard let userIdsDictionary = snapshot.value as? [String: Any] else { return }
userIdsDictionary.forEach({ (key, value) in
guard let userDictionary = value as? [String: Any] else { return }
let blockedList = Array(userDictionary.keys)
print(blockedList)
self.updateBlockList(blockedList: blockedList)
})
})
}
func updateBlockList(blockedList: [String]) {
updatedBlockList = blockedList
print(updatedBlockList)
}
fileprivate func fetchAllUserIds() {
let ref = Database.database().reference().child("users")
ref.observeSingleEvent(of: .value, with: { [weak self] (snapshot) in
guard var userIdsDictionary = snapshot.value as? [String: Any], let self = self else { return }
for item in self.updatedBlockList {
userIdsDictionary.removeValue(forKey: item)
}
userIdsDictionary.forEach({ (key, value) in
guard let userDictionary = value as? [String: Any] else { return }
let user = User(uid: key, dictionary: userDictionary)
self.fetchPostsWithUser(user: user)
})
}) { (err) in
print("Failed to fetch following user ids:", err)
}
}

I cant see values from firebase swift

Screen Shot 2019-04-01 at 4.45.08 PMenter image description hereI want to get the value from firebase that is stored I want to print it into a text label,
func fetchData(){
var ref: DatabaseReference!
ref = Database.database().reference()
guard let currentUid = Auth.auth().currentUser?.uid else {return}
Database.database().reference().child("users").child(currentUid).observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? Dictionary<String , AnyObject> else {return}
let uid = snapshot.value
let user = User(uid:uid as! String, dictionary: dictionary)
self.user = user
}) { (error) in
print(error.localizedDescription)
}
}
This is my another code to set the text label
func fetchData(){
var ref: DatabaseReference!
ref = Database.database().reference()
guard let currentUid = Auth.auth().currentUser?.uid else {return}
Database.database().reference().child("users").child(currentUid).observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? Dictionary<String , AnyObject> else {return}
let uid = snapshot.value
let user = User(uid:uid as! String, dictionary: dictionary)
self.userNameLabel.text = user.username
self.user = user
print(snapshot)
}) { (error) in
print(error.localizedDescription)
}
}
extra code to understand what I am doing
// user info stored
let userID = Auth.auth().currentUser?.uid
let userData = ["userName": userName,
"userAge ": userAge] as [String? : Any]
let values = [userID: userData]
let ref = Database.database().reference()
ref.child("users").childByAutoId().setValue(values)
}
I think you should use callbacks to communicate asynchronously with your controller.
In your example you get the uid by using "snpashot.value" but you should take the key of your dictionary instead.
Here is a similar example :
///Function that returns as callback the user stored in Firebase with a certain id.
func getUserFor(id: String, callback: #escaping (Bool, User?) -> Void) {
//Get the user in Firebase "user" collection with the specific id.
ref.child(Constants.userKey).child(id).observeSingleEvent(of: .value, with: { (userSnapshot) in
guard let userDictionnary = userSnapshot.value as? [String:Any] else { return callback(false, nil) }
let userId = userSnapshot.key
let userEmail = userDictionnary[Constants.emailKey] as? String
let user = User(id: userId, email: userEmail)
return callback(true, user)
}) { (error) in
print(error.localizedDescription)
return callback(false, nil)
}
}
I have found the answer I wasn't setting the user stored info in the firebase the right way.
let userID = Auth.auth().currentUser?.uid
let userData = ["userName": userName,
"userAge ": userAge] as [String? : Any]
let ref = Database.database().reference()
ref.child("users/\(userID ?? "")").setValue(userData)
}
//ref.child("users/(userID??"")").setValue(userData) // this was the error

Posts being loaded for all users in collection view firebase & swift

All I'm trying to do is fetch all the posts to the collection view that are within a certain radius of the current user. Currently I'm getting all the current users posts within the location but that is all. I can't figure out how to convert it to fetch all the posts from all the users.
FetchPostUserIds Is returning a snapshot of all the users and there UID
The geoFire query is only returning the postId from the current user. It shouldn't be I assume
Note: Updated Code
var PostKey: String?
var geoFire: GeoFire?
var regionQuery: GFRegionQuery?
var foundQuery: GFCircleQuery?
var geoFireRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
guard let uid = Auth.auth().currentUser?.uid else { return }
geoFireRef = Database.database().reference().child("posts").child(uid)
geoFire = GeoFire(firebaseRef: geoFireRef)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0] as CLLocation
let currentUserLocation = userLocation
let circleQuery = geoFire?.query(at: currentUserLocation, withRadius: 100.0)
_ = circleQuery?.observe(.keyEntered, with: { (key, location) in
self.PostKey = key
self.locationManager.stopUpdatingLocation()
})
}
fileprivate func fetchPostsWithUser(user: User) {
guard let key = PostKey else { return }
let ref = Database.database().reference().child("posts").child(user.uid).child(key)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
self.collectionView?.refreshControl?.endRefreshing()
guard let dictionary = snapshot.value as? [String: Any] else { return }
var post = Post(user: user, dictionary: dictionary)
post.id = key
self.posts.append(post)
self.posts.sort(by: { (post1, post2) -> Bool in
return post1.creationDate.compare(post2.creationDate) == .orderedDescending
})
self.collectionView?.reloadData()
}) { (error) in
print(error)
}
}
fileprivate func fetchPostUserIds() {
let ref = Database.database().reference().child("users")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let userIdKey = snapshot.value as? [String: Any] else { return }
userIdKey.forEach({ (key, value) in
Database.fetchUserWithUID(uid: key, completion: { (user) in
self.fetchPostsWithUser(user: user)
})
})
}) { (error) in
print(error)
}
}
Try to debug and look what you got in the snapshot in your function, and also what fetchUserWithUID return
fileprivate func fetchPostUserIds() {
let ref = Database.database().reference().child("users")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let userIdKey = snapshot.value as? [String: Any] else { return }
userIdKey.forEach({ (key, value) in
Database.fetchUserWithUID(uid: key, completion: { (user) in
self.fetchPostsWithUser(user: user)
})
})
}) { (error) in
print(error)
}
}
Maybe with some more information I can help you
You pass paremeter user: User to method fetchPostsWithUser, but you always use the current user
guard let uid = Auth.auth().currentUser?.uid else { return }
also note these
let ref = Database.database().reference().child("users")
ref.observe(.value, with: { (snapshot) in
will load every change so think about singleObserve

Fetch posts by postId from firebase with swift 4

All I'm trying to achieve is to have the posts inside my radius append to the collection view. Currently I'm getting all the postId when the user enters the radius but nothing is being append to the collection view and I can't figure out why. Any help is very much appreciated.
var posts = [Post]()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0] as CLLocation
let currentUserLocation = userLocation
let circleQuery = geoFire?.query(at: currentUserLocation, withRadius: 100.0)
_ = circleQuery?.observe(.keyEntered, with: { (key, location) in
guard let user = self.user else { return }
let ref = Database.database().reference().child("posts").child(key)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionaries = snapshot.value as? [String: Any] else { return }
var post = Post(user: user, dictionary: dictionaries)
post.id = key
self.posts.append(post)
self.posts.sort(by: { (post1, post2) -> Bool in
return post1.creationDate.compare(post2.creationDate) == .orderedDescending
})
}, withCancel: { (error) in
print("There was an error getting the posts:", error)
})
})
}
fileprivate func fetchPostUserIds() {
Database.database().reference().child("users").observe(.value, with: { (snapshot) in
guard let userIdsDictionary = snapshot.value as? [String: Any] else { return }
userIdsDictionary.forEach({ (key, value) in
let uidKey = key
self.geoFireRef = Database.database().reference().child("posts").child(uidKey)
self.geoFire = GeoFire(firebaseRef: self.geoFireRef)
})
}) { (err) in
print("Failed to get user Id", err)
}
}

Swift index out of range when refreshing

so ive been tring to solve this on my own for a few hours now. When ever i pull to refresh its crashes saying index out of range. Some people say its because of removing the arrays data before getting it and all that but only confused me further
here is my code
#objc fileprivate func fetchPostsWithUser() {
houses.removeAll()
myJobs.removeAll()
let ref = Database.database().reference().child("posts")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionaries = snapshot.value as? [String: Any] else { return }
dictionaries.forEach({ (key, value) in
guard let dictionary = value as? [String: Any] else { return }
var post = Post(dictonary: dictionary)
post.id = key
Database.database().reference().child(key).observeSingleEvent(of: .value, with: { (snapshot) in
if post.pickedUserId == Auth.auth().currentUser?.uid {
self.myJobs.append(post)
} else if post.hasPicked == true && post.pickedUserId != Auth.auth().currentUser?.uid {
print("taken out")
} else {
self.houses.append(post)
}
self.houses.sort(by: { (p1, p2) -> Bool in
return p1.creationDate.compare(p2.creationDate) == .orderedDescending
})
self.tableView.reloadData()
}, withCancel: { (err) in
print("Failed to fetch like info for post:", err)
})
})
}) { (err) in
print("Failed to fetch posts:", err)
}
}
A solution to this error will be greatly appreciated, thank you.