firebase snapshot value to dictionary - swift

In my app there is a data object named room that consists of the following properties...
class Room: NSObject {
var rid: String?
var owner: String?
var groupChatName: String?
var groupChatDescription: String?
var members: AnyObject?
}
Here is the corresponding JSON
"A632CA68-40D9-4F3A-B8C8-245457057443" : {
"groupChatDescription" : "Test Description",
"groupChatName" : "Test Name",
"members" : {
"WuqCAt4mM3h0P0X1m7hVZ7NQyLC2" : {
"username" : "Steve"
}
},
"owner" : "Steve"
},
When I retrieve these values from my database, I put them in a dictionary
func fetchAllRooms(){
Database.database().reference().child("rooms").observe(.childAdded, with: {(snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let room = Room()
room.rid = snapshot.key
room.setValuesForKeys(dictionary)
self.rooms.append(room)
print("\(room.members)")
DispatchQueue.main.async(execute: {
self.collectionView?.reloadData()
})
}
print("end of room snap")
}, withCancel: nil)
}
The data matches up correctly however handling the members is proving more difficult than I originally expected.
print("\(room.members)") Returns
Optional({
WuqCAt4mM3h0P0X1m7hVZ7NQyLC2 = {
username = "Steve";
};
})
That is a lot of extraneous text. Especially considering that this is only one member and I need to return a list of members in app.
What I believe would be best for my case is to create a dictionary for the members within the current dictionary. considering each member will have additional attributes such as a reference to their profile image.
So I could call something like print("\(room.members.usernames)") and get all the usernames and still be able to use the other attributes later on.
But I don't know if this is the best solution or even where to begin. I was hoping FireBase would have some built in methods to handle this but so far I haven't been able to find anything.
Any answers, suggestions, and or references are greatly appreciated.

Related

Manually Parsing a a JSON into an Object of a Struct

I'm a beginner in swift and I'm currently making an app that makes a web request. I've been trying to parse this JSON Data but the nested data is just really hard to wrap my head around:
"abilities": [
{
"ability": {
"name": "chlorophyll",
"url": "https://pokeapi.co/api/v2/ability/34/"
},
"is_hidden": true,
"slot": 3
},
{
"ability": {
"name": "overgrow",
"url": "https://pokeapi.co/api/v2/ability/65/"
},
"is_hidden": false,
"slot": 1
}
]
JSon Serialization Code
let jsonAny = try JSONSerialization.jsonObject(with: data, options: [])
guard let json = jsonAny as? [String: Any] else { return }
This is my attempt to manually parse the JSON Data
private func parsePokemonManual(json: [String: Any]) -> Pokemon {
let abilities = json["abilities"] as? [String: Any] ?? [String: Any]()
return Pokemon(abilities: abilities)
}
}
These are the structs that I made to hold the data.
struct Abilities {
let ability : Ability
struct Ability {
let name : String
}
}
How do I successfully parse the JSON Data into an object of Pokemon structure?
With this code so fat I am getting the error "Cannot convert the value of type '[String : Any]' to expected argument type '[Abilities]'. My problem is that I don't know what type to cast the abilities as and that my struct 'Abilities' is also incorrect.
There are 3 problems with your attempt although one might argue there is only 1, that you should use Codable instead but lets stay with JSONSerialization here. The problems are
You are reading the json wrong and should cast not to a dictionary but an array of dictionaries when accessing "abilities"
Your struct is to complicated, maybe because of the previous problem
Lastly, you can't cast into a custom type, you need to convert or map the data into your type by telling exactly what values to use and how because the compiler doesn't understand how to do it.
First the struct can be simplified to
struct Ability {
let name : String
}
And the rest is fixed in the function parsePokemonManual. First get "abilities" and cast to an array of dictionaries. Then map each item in the array by getting "ability" and casting it to a dictionary that is used to get the "name" value that is then used when creating an instance of Ability
private func parsePokemonManual(json: [String: Any]) -> [Ability] {
guard let abilities = json["abilities"] as? [[String: Any]] else {
return []
}
return abilities.compactMap { dict in
guard let ability = dict["ability"] as? [String: String], let name = ability["name"] else { return nil }
return Ability(name: name)
}
}

Structuring Firebase To Order By Time Last Liked And Two Most Recent Likes

I have a social app that I want display to the user the posts that were most recently liked and who were the two most recent people to like that post. Displaying something like "User A and User B liked and 31 others liked your post" where the 31 others liked the post less recently than User A and User B and this specific post was the most recent post of the user's to be liked.
I am trying to figure out the best way to structure firebase given these requirements. I was thinking I would store the lastLiked timestamp associated to the post in likeActivity and then use the timestamp as the key for the users who liked the post (see below).
"likeActivity" : {
"nIhx1SnChjapy4cbrD5sC1WIZXM2" : {
"-M0egnxw7TqEJoEwA0gG" : {
"lastLiked" : 1582337525620,
"userLikes" : {
"1582337525616" : "BmvRlWWuGRWApqFvtT8mXQlDWzz2",
"1582337525620" : "Ff0CxZhQzYVHuqbnsiOKwRAB01D2"
}
},
"-M0jMrisNrnB4usGeCaS" : {
"lastLiked" : 1582337525630,
"userLikes" : {
"1582337525630" : "Ff0CxZhQzYVHuqbnsiOKwRAB01D2"
}
},
"-M0jPBatN45YtfdyTXNM" : {
"lastLiked" : 1582337525616,
"userLikes" : {
"1582337525610" : "bz2E02wmmXQjVkxRF23T2SPkzSf2",
"1582337525616" : "WPOThFRRLDUCeJ8YVmyHFpGgnxI3"
}
}
}
}
Would this be the best way given my requirements from above? If so, I am having a ton of trouble retrieving these for my iOS app because when I call snapshot.children.allObjects I am not just getting the likes but also the lastLiked timestamp. How would I re-work the observeActivity function to pull data ordered by lastLiked and then ordered by timestamp. I read the documentation on ordering data in Firebase but I'm unsure how to apply it in my circumstance.
func observeActivity () {
guard let uid = Auth.auth().currentUser?.uid else {
return
}
let newActivity = DataService.ds.REF_LIKE_ACTIVITY.child("\(uid)")
newActivity.observe(.value, with: {(snapshot) in
self.posts = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot{
let postKey = snap.key
//self.posts.append(snap.key)
let userLikeData = newActivity.child("\(snap.key)").child("userLikes")
userLikeData.observe(.value, with: {(snapshot) in
if let newSnap = snapshot.children.allObjects as? [DataSnapshot] {
for valueSnap in newSnap {
//Users who have liked the post
print("SNAPTIVITY \(valueSnap.value!)")
let userId = valueSnap.value!
//self.userArray.append("\(userId)")
if self.activityDict["\(postKey)"] != nil {
self.activityDict["\(postKey)"]!.append("\(userId)")
} else {
self.activityDict["\(postKey)"] = ["\(userId)"]
}
}
let postData = DataService.ds.REF_POSTS.child(postKey)
postData.observe(.value, with: { (snapshot) in
if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
let key = snapshot.key
let post = Post(postKey: key, postData: postDict, isLiked: 0)
self.posts.append(post)
}
//self.feedTableView.reloadData()
self.activityTableView.reloadData()
})
}
})
}
}
})
}
In most social network application each user can only like an individual post at most once. Your current data model for these likes is:
"userLikes" : {
"1582337525616" : "BmvRlWWuGRWApqFvtT8mXQlDWzz2",
"1582337525620" : "Ff0CxZhQzYVHuqbnsiOKwRAB01D2"
}
This model allows a single user to like the same post multiple times. And while you can prevent this from happening in your application code, there's no way to enforce it in security rules.
For this reason, a pretty hard rule when modeling data in Firebase&Firestore is: if something must be unique, it must be the key of the child node/document.
So based on that, I'd model this fragment as:
"userLikes" : {
"BmvRlWWuGRWApqFvtT8mXQlDWzz2": 1582337525616,
"Ff0CxZhQzYVHuqbnsiOKwRAB01D2": 1582337525620
}
You'll note that this now also allows you to store the timestamp as a number, which prevents all kind of possible sorting problems down the line.
I assume your data structure is:
likeActivity
$uid
$postId: ...
Since you're retrieving a list of posts for the current user, you can only order the resulting posts on values that are at a fixed path under each post.
So you can sort the posts on their lastLiked, but you can't then determine the order in which the userLikes under that are returned. You'll have to reorder those results in your application code to determine the most recent like(r).

Cannot deal with Firebase asynchronous API-call problem relating to data retrieval despite using completion blocks

My Firebase real-time database is structured like this:
{
"friends" : {
"-LhZw8ryHbE-VIeh1kx6" : {
"members" : [ "3rTK12GBEQf8WMbLEdAz4Pftkxs1", "guHd7whcqyfFjfkduPoCmryLe0I3" ],
"title" : "Ansh’s Trials"
},
"-LhdBeCVRfDVQBtoAeuf" : {
"members" : [ "3rTK12GBEQf8WMbLEdAz4Pftkxs1", "guHd7whcqyfFjfkduPoCmryLe0I3" ],
"title" : "Trial 2"
},
},
"users" : {
"3rTK12GBEQf8WMbLEdAz4Pftkxs1" : {
"email" : "anshgodha77#gmail.com",
"fullname" : "Ansh Godha",
"provider" : "Firebase"
},
"guHd7whcqyfFjfkduPoCmryLe0I3" : {
"email" : "harvey#davidson.com",
"fullname" : "Harvey Davidson",
"provider" : "Firebase"
}
}
}
Now, in the app, I create user groups, and each group is added under 'friends' in the database, as you can see. I am trying to retrieve all the groups in a table view. In this table view, I set the group title as the "title" value for the corresponding group in the "friends" subtree. Given the group key, setting the title is straightforward. However, it seems like I am having problems with retrieving the NAMES of the people in the group. Note that, to store a group in my model, I store the UIDs of the users in that particular group (refer to JSON tree). Here is how I attempt to do it (refer to the pointers below for additional information on the code):
func getUserFullname(forUID uid: String, handler: #escaping (_ username: String) -> ()) {
print(5)
self.REF_USERS.observeSingleEvent(of: .value) { (userSnapshot) in
print(6)
guard let userSnapshot = userSnapshot.children.allObjects as? [DataSnapshot] else { return }
print(7)
for user in userSnapshot {
print(8)
if user.key == uid {
handler(user.childSnapshot(forPath: "fullname").value as! String)
}
}
}
}
func getFullnameList(fromUIDArray uidarr: [String], completion: #escaping (_ nameArr: [String]) -> ()){
var namearr = [String]()
print(1)
for uid in uidarr {
print(2)
DataService.instance.getUserFullname(forUID: uid) { (returnedFullName) in
namearr.append(returnedFullName)
}
print(3)
}
print(4)
completion(namearr)
}
REF_USERS was defined as Database.database().reference().child("users")
DataService is a singleton in which these 2 methods have been defined.
I know the logic behind my code is correct, because when I print the results, I can see the correct names. It's just that I see the names after all the other parts of the code have finished executing. Essentially, nameArr is an empty array even at the end of the second method.
So, how do I make it so that the userFullNames get passed correctly to nameArr? I tried referring to all the other SO posts and they all seemed to use the completion handler this way. Thanks!
PS: I am extremely new to Swift and IOS AppDev, so I'm sorry if this is still a very common question! But I tried implementing different things I found online (like DispatchQueues) but couldn't succeed :(. Also, this is one of my first StackOverflow posts, so I'm sorry if it lacks detail. Will post any more information needed!
I would suggest a different structure. Arrays are inherently challenging in NoSQL databases and there are often better options.
assuming a users node
users
uid_0
name: "Bill"
uid_1
name: "Ted"
and a proposed groups structure
groups
group_0
name: "My Most Excellent Group"
members:
uid_0: true
uid_1: true
Then some code to read the groups, print the title, then iterate over each child in the members list, get that members name from the users node and print it. I added some comments so you can follow the code a bit easier.
func readGroups() {
let groupsRef = self.ref.child("groups")
groupsRef.observeSingleEvent(of: .value, with: { snapshot in //read all groups at once
let allGroupsArray = snapshot.children.allObjects as! [DataSnapshot] //put each child into an array as a DataSnapshot
for groupSnap in allGroupsArray { //iterate over the array so we can read the group name and group members
let groupName = groupSnap.childSnapshot(forPath: "title").value as? String ?? "No Group Name"
print("group: \(groupName) has the following members")
let members = groupSnap.childSnapshot(forPath: "members") //get the members child as a DataSnapshot
let allMembers = members.children.allObjects as! [DataSnapshot] //put the members into an array
for memberSnap in allMembers {
let memberUid = memberSnap.key //get the uid of each member
let memberRef = self.ref.child("users").child(memberUid) //get a reference to the member
memberRef.observeSingleEvent(of: .value, with: { childSnap in //read the member in, print name
let name = childSnap.childSnapshot(forPath: "name").value as? String ?? "No Name"
print(" name: \(name)")
})
}
}
})
}
and the output will be
group: My Most Excellent Group has the following members
name: Bill
name: Ted

Search for sub child in firebase database

Firebase Structure
Hi, I am try to work out how to query jobBrand & jobName in my Firebase Database (Structure Attached) and store it in a tableView. I am going to store more information under each Job Brand so I would like to keep the structure this way if possible?
So far, I can get tableView to read the 2 fields if they are one level up, so the structure would be:
tbaShootApp -> Jobs -> Job Brand > data.
I cannot work out to query down another level and store it in the tableView. Is this possible?
I am using a dictionary to store the job information:
class Job: NSObject {
var id: String?
var jobBrand: String?
var jobName : String?
var director : String?
var jobInfo : jobInfo?
init(dictionary: [String: AnyObject]) {
self.id = dictionary["id"] as? String
self.jobBrand = dictionary["jobBrand"] as? String
self.jobName = dictionary["jobName"] as? String
self.director = dictionary["Director"] as? String
}
}
Here is the code to query the data - I have the function 'fetchJobs' in my superViewDidLoad.
func fetchJobs() {
Database.database().reference().child("Jobs").observe(.childAdded) { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let job = Job(dictionary: dictionary)
job.id = snapshot.key
self.jobs.append(job)
//this will crash because of background thread, use dispatch_async to fix
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}
}
JSON
{
"Jobs" : {
"Candycrush" : {
"cameraInfo" : {
"cameraBody" : "A",
"cameraBrand" : "Arri",
"cameraType" : "Alexa"
},
"jobInfo" : {
"jobBrand" : "CandyCrush",
"jobName" : "Winter"
}
},
"Honda" : {
"cameraInfo" : {
"cameraBody" : "A",
"cameraBrand" : "Arri",
"cameraType" : "Alexa XT"
},
"jobBrand" : "Honda",
"jobName" : "Comet"
},
"WWF" : {
"cameraInfo" : {
"cameraBody" : "A",
"cameraBrand" : "Red",
"cameraType" : "Epic"
},
"jobInfo" : {
"jobBrand" : "WWF",
"jobName" : "Eye"
}
}
}
}
There's a long way to go but maybe this will help:
.child("Jobs").observe(.childAdded)
It will let you know each time a new Jobs is added (Candycrush, Honda etc).
(Note - apart from anything else, you very likely also want to observe removals on that list, also.)
If you are making a table (or whatever ... some sort of list, paging thing, collection of tabs, or the like):
almost certainly each row of the table will, on it's own, want to observe that job.
So the first row, would observe for changes in Jobs/Candycrush
So the second row, would observe for changes in Jobs/Honda
And so on. Each table row (or screen, panel, bubble, tab, or whatever it is) would, on it's own, observe that thing.
Incidentally, almost certainly the "first level" header there (where you have Honda, Candycrush etc) would be an id string. (Just use a UUID, or let Firebase do it.) And then a field "Title" would be Honda etc. It would be very unusual to use the actual title as the sort of ID there. (Note that, apart from anything else, you then can't change/edit the title!).
UPDATE
Since you have added a lot more information since I posted my answer. It is now obvious that you want to query deeper. Additionally, since you posted the actual JSON it is now obvious that the JobBrand node is dynamic. You can query one level below an unknown child. You can read about that here.
I'm going to change .observe(.childAdded) to .observeSingleEvent(of: .value) because you are querying so deep I doubt you want to observe that node, but I could be wrong. Changing this will pull the data in once and only once. If you want to update that value you will have to query again.
You want a query like this:
Database.database().reference().child("Jobs").queryOrdered(b‌​yChild: "jobInfo/jobBrand").queryEqual(toValue: "JobBrandYouWant").observeSingleEvent(of: .value, with: { snapshot in
if let dictionary = snapshot.value as? [String: AnyObject] {
let job = Job(dictionary: dictionary)
job.id = snapshot.key
self.jobs.append(job)
}
})
ORIGINAL ANSWER
You current query is going to return all of the data under jobs. Which includes the nodes Job Brand -> jobinfo -> etc.
If you are trying to get less data then you need to know either the JobBrand, jobinfo or both. However, I think you want all of the jobs and your query just isn't working.
You current query fails because your dictionary contains everything under "Jobs" not just one job. You want to loop over the data snapshot and
get each job before you call init.
Database.database().reference().child("Jobs").observe(.childAdded, with: { snapshot in
for child in snapshot.children { // over over the snapshot and cast each "job" to it's own dictionary
let child = child as? DataSnapshot
if let key = child?.key {
if let dictionary = child?.value as? [String: AnyObject] {
let job = Job(dictionary: dictionary)
job.id = key
self.jobs.append(job)
}
}
}
})
The documentation provides this example for looping over a snapshot
_commentsRef.observe(.value) { snapshot in
for child in snapshot.children {
...
}
}

How to query thousands of values and only return ones in array - Firebase Swift

In firebase realtime database, I have data as such:
"users" : {
"37KfZKDwrieIEKI9juAC4Xm8aPi1" : {
"isConnected" : false,
"isGuestUser" : false,
"lastOnline" : 1510250272022,
"profilePicture" : "5a039030515e78653148",
"userID" : "37KfZKDwrieIEKI9juAC4Xm8aPi1",
"username" : "adsfasdfasdf"
},
"4D1GNiRH5NeRxpmTNg6JhJ3iTck1" : {
"isConnected" : false,
"isGuestUser" : true,
"lastOnline" : 1510077502788,
"profilePicture" : "5a01f2648278b6652011",
"userID" : "4D1GNiRH5NeRxpmTNg6JhJ3iTck1",
"username" : "ihoho"
},
"5UA3INZ7i0dnNtgX0ai5ABhjxh43" : {
"isConnected" : false,
"isGuestUser" : true,
"lastOnline" : 1512610102474,
"profilePicture" : "5a14df775a34f2388873",
"userID" : "5UA3INZ7i0dnNtgX0ai5ABhjxh43",
"username" : "jlkjlkjlkj"
},...
I am using an external API that returns a Json that looks like this
"candidates" : [
{
"enrollment_timestamp" : "1510182689539",
"subject_id" : "37KfZKDwrieIEKI9juAC4Xm8aPi1",
},
{
"enrollment_timestamp" : "1513557650425",
"subject_id" : "CKUVZ7XtY9VKJakn1lBV7MVW1702",
},
{
"enrollment_timestamp" : "1507578748901",
"subject_id" : "l7VDdtGFpMe8BRbrlCyAciTvONk1",
},...
The ultimate goal is to get all the users from the json from the external api that are online. This requires listening to the 'isConnected' endpoint in each user, and determining if it is true or false.
Now this is impossible using firebase and my current data structure, because firstly firebase does not support multiple query parameters, so I cannot do where userID = subjectID && where isConnected == true, and secondly, more importantly, firebase does not let me do the equivalent of WHERE IN, i.e. mapping userID's to an array of potential userIDs supplied client side (fyi subjectID === userID)
So what I did was restructure my data like so;
"onlineUsers" : {
"Aze1x7jTZIbPyyPmlUYWVdEyAd73" : true,
"CQdmMxkmqBerRGOQpFblx7SO4D33" : true,
"EptMK62Kt1Sp1EIb5meuKHVpUqs1" : true,
"J2X65KauDlSvkN4Yp5V4IF0sTnx1" : true,
"KnYEqsekY9YXV3ayOx082xw8VQX2" : true,
"aGLrKH31YvRKrB8KYQmZ4sA122m1" : true,
"ab3JZyw9YMdpW3mXkZc2BjYkxej2" : true,
"gpQic1EzSnXL9x5DhaoXxcWrGF22" : true,
"qQaBPMaDOrXrWddsijfMJWusuGG3" : true,
"tDWEUoKS4mUdQ1bWeiLTlhwCSoD3" : true
},
Now all I have to do to get all online users that are in the external api json is query onlineUsers with the condition parameter checking by the key. That way I know if the result is null, the user is not online:
static func queryDatabase(child: String, queryEqual: String, keyOf: Int, completionHandler: #escaping (_ return: AnyObject?, _ error: String?) -> Void){
print("querying db with child ", child)
let ref = databaseReference.child(child).queryOrderedByKey().queryEqual(toValue: queryEqual)
ref.observe(.value, with:{ (snapshot: DataSnapshot) in
print("subjectID: ", queryEqual, "at key ", keyOf)
print("queryResult", snapshot)
if let value = (snapshot.value as? [String: AnyObject])?[queryEqual] {
print("unwrapped snapshot dict value from key: ", value)
completionHandler(value, nil)
}else{
print("no value for key \(queryEqual) so setting return as nil")
completionHandler(nil, nil)
}
}){ (error) in
print(error.localizedDescription)
completionHandler(nil, error.localizedDescription )
}
}
This function would be called simple by looping through the external api json, and calling this function ^^ every iteration, something like:
for (key, valueSubjectID) in arrayOfOrderedMatches.enumerated(){
//call function queryDatabase here
queryDatabase(child: "onlineUsers", queryEqual: valueSubjectID, keyOf: key, completionHandler:{ (response, error) in
//it would return the user if they were online here
)}
}
Now. This works. It is the most efficient way I can possible think of doing it after looking around the internet and considering every possibility. However, now onto the big problem: the json from the api can be thousands and thousands of users long. This means thousands of listeners would be being attached to check each individual user to see if they are online. This, as I have been told by a Firebase developer, is not ideal. I should not be attaching thousands of listeners. Additionally, for some reason, listeners stop being added at around 3500, i'm guessing because it bugs out. I can't remove the listeners if the query returns null (ie offline) because of the way the cache offline persistence works, and even if I could I don't think this would solve the problem. Is there any way this problem can be solved?
Let me restate the objective.
The app is provided a large list of user id's (as JSON) and the goal is to know which of those users are online.
Here's two options:
We start with a users node
users
uid_0
name: "Frank"
online: true
uid_1
name: "Jeff"
online: false
When the JSON of the users we want to check is received, we convert it to an Array for easy access.
Then, we have a couple of options
1) Iterate over the array and observeSingleEvent for each uid to get it's current status. This won't be a query since we can directly access the uid so it will be fairly lightweight by comparison to a query.*
let arrayToTest = [String]() //the array of uid's to test
for uid in arrayToTest {
let thisUserRef = self.ref.child("users").child(uid)
thisUserRef.observeSingleEvent(of: .value, with: { snapshot in
let dict = snapshot.value as! [String: Any]
let status = dict["online"] as! Bool
print("uid: \(uid) online status is: \(status)")
})
}
2) Let Firebase do the heavy lifting by adding a .childAdded event to the users node, which will iterate over all of the users one at a time.
Compare the uid in the snapshot to the uid's in the array and if it matches, get it's status (on/offline) and if it doesn't exist in the array, ignore it.
let usersRef = self.ref.child("users")
let arrayToTest = [String]() //the array of uid's to test
usersRef.observe(.childAdded, with: { snapshot in
let dict = snapshot.value as! [String: Any]
let uid = dict["user_id"] as! String
if arrayToTest.contains(uid) {
let status = dict["online"] as! Bool
print("uid: \(uid) online status is: \(status)")
}
})
Option 2) will generally be better as it's only loading one at a time and Firebase is doing all of the work - we're just checking to see if the uid from the snapshot exists in code.
3)
As a third option we can leverage a query. Note that in the first two options we retrieved our data using the lightweight observe function. Queries are heavier by comparison and utilize more resources - however, the snapshot results are limited to only those users that are logged in, and if there are a significant amount of users may be the best option.
let usersRef = self.ref.child("users")
let queryRef = usersRef.queryOrdered(byChild: "online").queryEqual(toValue: true)
let arrayToTest = [String]() //the array of uid's to test
queryRef.observe(.childAdded, with: { snapshot in
let dict = snapshot.value as! [String: Any]
let uid = dict["user_id"] as! String
if arrayToTest.contains(uid) {
print("uid: \(uid) online status is: true")
}
})
*Firebaser's will frown on 1) as they strongly recommend against doing observes in a tight loop. So 2) if you want to get confirm every user exists and 3) if you're just interested in online users.