firebase swift queries in queries performance - swift

I am new to Firebase and relatively new to Swift.
I have firebase set up as below. I have users, followers and blocked users. I take care of the followers in the UITableViewCell class.
I am wondering, before I go any further: how does performance get affected by putting observers in observers in queries in queries. (Hope these are the correct terms) . Is below the right way to go about it?(the most efficient way). It works, but also seems to stutter a bit. I appreciate any feedback.
{
"BlockedByUsers" : {
"ba1eb554-9a81-4a74-bfd9-484a32eee13d" : {
"97fee08f-19b2-4eb5-9eab-4b1985c22595" : true
}
},
"Dates" : {
"1457635040" : {
"97fee08f-19b2-4eb5-9eab-4b1985c22595" : true
},
},
"Locations" : {
"97fee08f-19b2-4eb5-9eab-4b1985c22595" : {
".priority" : "u14dkwm41h",
"g" : "u14dkwm41h",
"l" : [ 51.05521018175982, 3.720297470654139 ]
},
},
"Users" : {
"97fee08f-19b2-4eb5-9eab-4b1985c22595" : {
"blockedUsers" : {
"ba1eb554-9a81-4a74-bfd9-484a32eee13d" : true
},
"following" : {
"51879163-8b35-452b-9872-a8cb4c84a6ce" : true,
},
"fullname" : "",
"dates" : 1457635040,
"location" : "",
},
}
}
my Swift code with the multiple queries I'm worried about:
var usersRef: Firebase!
var userFollowingRef: Firebase!
var blockedByUsersRef: Firebase!
var datesRef: Firebase!
var geofireEndRef: Firebase!
var geoFireEnd: GeoFire? {
return GeoFire(firebaseRef: geofireEndRef)
}
var dateRangeStart = Int()
var dateRangeEnd = Int()
override func viewDidLoad(){
super.viewDidLoad()
usersRef = DataService.ds.REF_USERS
userFollowingRef = DataService.ds.REF_CURRENTUSER_FOLLOWING
blockedByUsersRef = DataService.ds.REF_BLOCKED_BY_USERS
datesRef = DataService.ds.REF_DATES
geofireEndRef = DataService.ds.REF_GEOFIREREF_END
}
override func viewWillAppear(animated: Bool){
super.viewWillAppear(animated)
if userdefaultsUid != nil
{
geoFireEnd!.getLocationForKey(userID, withCallback: { (location, error) in
if (error != nil)
{
print("An error occurred getting the location for \(self.userID) : \(error.localizedDescription)")
} else if (location != nil)
{
self.updateUsersWithlocation(location)
} else
{
print("GeoFire does not contain a location for \(self.userID)")
self.updateUsersWithoutLocation()
}
})
}
}
func updateUsersWithlocation(location: CLLocation)
{
var allKeys = [String]()
let locationQuery = self.geoFireEnd!.queryAtLocation(location, withRadius: 100.0)
locationQuery.observeEventType(GFEventType.init(0), withBlock: {(key: String!, location: CLLocation!) in
allKeys.append(key)
self.datesRef.queryOrderedByKey().queryStartingAtValue(String(self.dateRangeStart)).queryEndingAtValue(String(self.dateRangeEnd)).observeEventType(.ChildAdded, withBlock: {
snapshot in
self.users.removeAll(keepCapacity: true)
self.newKeys.removeAll()
self.tableView.reloadData()
for datesKey in snapshot.children
{
self.usersRef.childByAppendingPath(datesKey.key!).observeSingleEventOfType(.Value, withBlock: { snapshot in
if let key = datesKey.key where key != self.userID
{
if allKeys.contains(key!) {
let newuser = FBUser(userKey: key!, dictionary: snapshot.value as! [String : AnyObject])
self.blockedByUsersRef.childByAppendingPath(key).childByAppendingPath(self.userID).observeSingleEventOfType(.Value, withBlock: { (snapshot) -> Void in
if let _ = snapshot.value as? NSNull
{
// we have not blocked this one
self.blockedByUsersRef.childByAppendingPath(self.userID).childByAppendingPath(key).observeSingleEventOfType(.Value, withBlock: { snapshot in
if let _ = snapshot.value as? NSNull
{
// we are not blocked by this one
if self.newKeys.contains(newuser.userKey) {}
else
{
self.users.append(newuser)
self.newKeys.append(newuser.userKey)
}
}
self.tableView.reloadData()
})
}
})
}
}
})
}
})
})
}
In essence users can be at a certain place at a certain date. They put down the date they are going to be there, as explained in code below. that date may overlap with other users that are going to be in that area, in a period ranging of say 7 days before until 21 days after. those users can be followed, blocked. but I’m getting those to display in the tableView. If they put in a different date or place, a different set of users will pop up.
if let userStartDate = beginningDate as? Double
{
let intUserStartDate = Int(userStartDate)
dateRangeStart = intUserStartDate - 604800
dateRangeEnd = intUserStartDate + 1814400
print(dateRangeStart, intUserStartDate, dateRangeEnd)
updateUsers()
}
else
{
updateUsersWithoutDate()
}

This may or may not be an answer or help at all but I want to throw it out there.
Given that you want to really look for two things: locations and times, we need some mechanics to handle it.
The locations are more static; i.e. the bowling ally will always be the bowling ally and the times are dynamic and we need a range. So, given a structure
{
"events" : {
"event_0" : {
"loc_time" : "bowling_5"
},
"event_1" : {
"loc_time" : "tennis_7"
},
"event_2" : {
"loc_time" : "tennis_8"
},
"event_3" : {
"loc_time" : "dinner_9"
}
}
}
This structure handles both criteria. You can easily query for all nodes that have location of tennis at a time of 7. You can also query the range for tennis from start time of 6 and end time of 9, which will return tennis_7 and tennis_8
Here's some ObjC code to do just that
Firebase *ref = [self.myRootRef childByAppendingPath:#"events"];
FQuery *query = [[[ref queryOrderedByChild:#"loc_time"]
queryStartingAtValue:#"tennis_6"] queryEndingAtValue:#"tennis_8"];
[query observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
NSLog(#"%#", snapshot);
}];
You can extrapolate from this substituting your locations for location and distance or timestamps for the time.
Another modification (and this may be obvious but stating it for clarity) is to use a reference to your locations instead of the actual name (bowling, tennis); i.e.
events
"event_0" : {
"loc_time" : "-JAY8jk12998f_20160311140200" // locationRef_timestamp
},
locations
-JAY8jk12998f : {
"loc_name": "Fernando's Hideaway"
}
Structuring your data in the way to want to get to it can significantly reduce your code (and the complexity of queries within queries etc).
Hope that helps.

Related

How to upload new multiple nodes with multiple auto-id

Im trying to update multiple nodes with multiple auto-id by using for-loop. However it always fail. i cant see anything updated on databse.
Is there any other way to implement it?
let ref = Database.database().reference().child("kardexes").child(newKardex.id)
ref.observeSingleEvent(of: .childAdded, with: { (snapshot) in
if (snapshot.exists()){
for treatment in self.treatments {
self.treatmentId = ref.child("treatments").childByAutoId().key
var treatmentData = FirebaseDataType()
treatmentData["name"] = treatment.name
ref.child("treatments").child(self.treatmentId!).setValue(treatmentData){ (error, ref) in
if let error = error {
Log.debug(" >>> error \(error.localizedDescription)")
}
}
}
} else{
print("snapshot doesnt exist")
}
})
I expect to get the following result, but nothing get updated
kardexes
|
-LkcSD2KJLwbCj8KAdsd
|-treatments
|-"-Lkc5MFEGsfbCj8KAmbo"
|-name:"abc"
|-"-Lk5sKCKJLwbCj8KAofj"
|-name:"def"
|-"-Lk5sKFOELwbCj8KAjgu"
|-name:"ijk"
This question is a bit unclear but I think you're asking how to create the 'kardexes' node so it looks like the structure presented in you question.
If so, here's the code that does that
func createKardexesNode() {
let treatmentArray = ["abc", "def", "ghi"]
let ref = self.ref.child("kardexes").child("-LkcSD2KJLwbCj8KAdsd").child("treatments")
for treatment in treatmentArray {
let childRefToAdd = ref.childByAutoId()
childRefToAdd.child("name").setValue(treatment)
}
}
running this code generates a node in Firebase that looks like this
{
"kardexes" : {
"-LkcSD2KJLwbCj8KAdsd" : {
"treatments" : {
"-Ll2dsJivnsH9QRM6MfV" : {
"name" : "abc"
},
"-Ll2dsJivnsH9QRM6MfW" : {
"name" : "def"
},
"-Ll2dsJivnsH9QRM6MfX" : {
"name" : "ghi"
}
}
}
}
}
note that self.ref is a class var that points to the root ref of my Firebase. Substitute your own.

queryOrdered doesn't always return data on tableViewCell in correct order

I am trying to order data on the notifications page from new to old based on timestamp, right now - when i run it, sometimes it is in the correct order but other times it is random and incorrect. Please let me know if there is anything i can add to make sure it runs smoothly at all times, thank you in advance :)
My firebase JSON structure is:
"notifications" : {
"BlP58dSQGCUBwhst91yha43AQu42" : {
"-LeNCQJ6nUSR1263iKyj" : {
"from" : "FRuuk20CHrhNlYIBmgN4TTz3Cxn1",
"timestamp" : 1557331817,
"type" : "true"
},
"-LeNCRwNpNaXm2qhYPpu" : {
"from" : "FRuuk20CHrhNlYIBmgN4TTz3Cxn1",
"timestamp" : 1557331824,
"type" : "true"
},
"BlP58dSQGCUBwhst91yha43AQu42-FRuuk20CHrhNlYIBmgN4TTz3Cxn1" : {
"from" : "FRuuk20CHrhNlYIBmgN4TTz3Cxn1",
"timestamp" : 1557331811,
"type" : "false"
}
},
My code:
func observeNotification(withId id: String, completion: #escaping (Notifications) -> Void) {
REF_NOTIFICATION.child(id).queryOrdered(byChild: "timestamp").observe(.childAdded, with: { snapshot in
if let dict = snapshot.value as? [String: Any] {
let newNoti = Notifications.transform(dict: dict, key: snapshot.key)
completion(newNoti)
}
})
}
Edit:
The function is then called in the NotificationViewController like this:
func loadNotifications() {
guard let currentUser = Api.User.CURRENT_USER else { return }
Api.Notification.observeNotification(withId: currentUser.uid , completion: { notifications in
guard let uid = notifications.from else { return }
self.fetchUser(uid: uid, completed: {
self.notifications.insert(notifications, at: 0)
self.tableView.reloadData()
})
})
}
and loadNotifications() is called in the viewDidLoad
UPDATE:
Trying to do it using "for child in snapshot.children" but nothing is showing on notifications page anymore
func observeNotification(withId id: String, completion: #escaping (Notifications) -> Void) {
REF_NOTIFICATION.child(id).observe(.value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
let notificationOrder = self.REF_NOTIFICATION.child(key).queryOrdered(byChild: "timestamp")
notificationOrder.observeSingleEvent(of: .value, with: { snapshot in
if let dict = snapshot.value as? [String: Any] {
print(dict)
let newNoti = Notifications.transform(dict: dict, key: snapshot.key)
completion(newNoti)
}
})
}
})
}
}
The DataSnapshot that you get back from Firebase contains three types of information:
The key of each child that matched the query.
The value of each child that matched the query.
The order in which the children result from the query.
When you convert the entire result to a dictionary (dict = snapshot.value as? [String: Any]), there is only place for the keys and the values. So the order of the children gets lost.
To maintain the order of the child nodes, loop over the query results of snapshot.children as shown in the documentation on listening for lists of data with a value event.

Swift: Search for a specific value in Firebase Database & find all associated data

I have data uploading to my Database. I'm trying to implement Search functionality that I can search for something by the name, and if the name is found then autopopulate textfields with the data corresponding to that name. So for example if I search 'Pepsi Max' I want to find pepsi max in my database and then display the price/location/rating etc.
I currently have a Search function but that just searches the entire db and prints all values.
func searchT() {
let pub = pubName.text
print(pub)
let databaseRef = Database.database().reference().child("Drinks")
let query = databaseRef.queryOrdered(byChild: "pub").queryStarting(atValue: pub).queryEnding(atValue: "\(String(describing: pub))\\uf8ff")
query.observeSingleEvent(of: .value) { (snapshot) in
guard snapshot.exists() != false else { return }
print(snapshot.value as Any)
DispatchQueue.main.async {
guard let dict = snapshot.value as? [String:Any] else {
print(snapshot)
return
}
let pubName = dict["pub"] as? String
let pubLocation = dict["location"] as? String
let price = dict["price"] as? String
let rating = dict["rating"] as? String
let comment = dict["comment"] as? String
self.pubName.text?.append(pubName!)
self.pubLocation.text?.append(pubLocation!)
self.price.text?.append(price!)
self.rating.text?.append(rating!)
self.comment.text?.append(comment!)
}
}
}
You will notice that in this function I'm searching by the data 'pubName' (which I think I'm setting incorrectly in the first line, but not sure how to correct it). This function crashes on the first line of setting the textViews to a value as there's 'nil while unwrapping an Optional value'
How can I search by pubName , locate the corresponding value and then set the textfields as the remaining data in the db relating to the searched value.
Thanks in advance, E
1. Realtime Database
Since you haven't included the structure of your database, I assume you have a database structure for drinks like below:
Screenshot of my Realtime database for this answer
{
"Drinks" : {
"-LYiUHm4vtrB3LqCBxEc" : {
"location" : "toronto",
"name" : "pepsi max",
"price" : 13.5,
"rating" : 3.6
},
"-LYiUHm5Lgt3-LENTdBZ" : {
"location" : "new york",
"name" : "diet coke",
"price" : 15.45,
"rating" : 5
},
"-LYiUHm5Lgt3-LENTdB_" : {
"location" : "chicago",
"name" : "mountain dew",
"price" : 2,
"rating" : 2
},
"-LYiUHm5Lgt3-LENTdBa" : {
"location" : "vancouver",
"name" : "sprite",
"price" : 6.98,
"rating" : 4.5
}
}
}
2. Swift 4.0
Now, to search any drink by name use below code:
func search(drinkName: String) {
let databaseRef = Database.database().reference().child("Drinks")
let query = databaseRef.queryOrdered(byChild: "name").queryStarting(atValue: drinkName).queryEnding(atValue: "\(drinkName)\\uf8ff")
query.observeSingleEvent(of: .value) { (snapshot) in
guard snapshot.exists() != false else { return }
//print(snapshot.value)
DispatchQueue.main.async {
// Update TextFields here
}
}
}
The \uf8ff character used in the query above is a very high code point in the Unicode range. Because it is after most regular characters in Unicode, the query matches all values that start with a b.
Source: https://firebase.google.com/docs/database/rest/retrieve-data
Note: queryOrderedByChild() is case-sensitive. It is nice practice to save all fields lowercased in database as this makes it easier to query data. You can always format strings in front end.
3. Add ".indexOn" to Realtime Database's Rules
In order to above query to work and achieve better performance, you need to set the index on the field that you are going to search by.
You can do this by going to Rules tab and adding index like below:
{
"rules": {
".read": true,
".write": true,
"Drinks": {
".indexOn": "name"
}
}
}
Source: More information on indexing data
Updated Answer for your updated question:
func searchT() {
// You must cast pub variable as String.
guard let pub: String = pubName.text else { return }
print(pub)
let databaseRef = Database.database().reference().child("Drinks")
let query = databaseRef.queryOrdered(byChild: "pub").queryStarting(atValue: pub).queryEnding(atValue: "\(String(describing: pub))\\uf8ff")
query.observeSingleEvent(of: .value) { (snapshot) in
guard snapshot.exists() != false else {
print("failing here")
return }
print(snapshot.value as Any)
DispatchQueue.main.async {
guard let dict = snapshot.value as? [String:Any] else {
print(snapshot)
return
}
let pubName = dict["pub"] as? String
let pubLocation = dict["location"] as? String
let price = dict["price"] as? String
let rating = dict["rating"] as? String
let comment = dict["comment"] as? String
}
}
}

Firebase Realtime Database in Swift

After several hours of trying to figure out what's happening without finding an answer to fill my void anywhere, I finally decided to ask here.
While I assume I do have a concurrency issue, I have no clue as to how to solve it...
I have an application trying to pull data from a Firebase Realtime Database with the following content:
{
"products" : {
"accessory" : {
"foo1" : {
"ean" : 8793462789134,
"name" : "Foo 1"
},
"foo2" : {
"ean" : 8793462789135,
"name" : "Foo 2"
}
},
"cpu" : {
"foo3" : {
"ean" : 8793462789115,
"name" : "Foo 3"
}
},
"ios" : {
"foo4" : {
"ean" : 8793462789120,
"name" : "Foo 4"
},
"foo5" : {
"ean" : 8793462789123,
"name" : "Foo 5"
}
}
}
}
I have a data model in Product.swift:
class Product {
var identifier: String
var category: String
var ean: Int
var name: String
init(identifier: String, category: String, ean: Int, name: String) {
self.init(identifier: identifier)
self.category = category
self.ean = ean
self.name = name
}
}
I want to fetch the data in another class called FirebaseFactory.swift. I plan to use to communicate with Firebase:
import Foundation
import FirebaseDatabase
class FirebaseFactory {
var ref = Database.database().reference()
func getAvailableProducts() -> [Product] {
var products = [Product]()
var data: DataSnapshot = DataSnapshot()
self.ref.child("products").queryOrderedByKey().observeSingleEvent(of: .value) { (snapshot) in
data = snapshot
// 1st print statement
print("From within closure: \(data)")
}
// 2nd print statement
print("From outside the closure: \(data)")
// Getting the products yet to be implemented...
return products
}
}
For now, I am simply trying to call the getAvailableProducts() -> [Product] function from one of my view controllers:
override func viewWillAppear(_ animated: Bool) {
let products = FirebaseFactory().getAvailableProducts()
}
My Problem now is that the 2nd print is printed prior to the 1st – which also means that retrieving the data from the snapshot and assigning it to data variable does not take place. (I know that the code to create my Product objects is missing, but that part actually is not my issue – concurrency is...)
Any hints – before I pull out any more of my hairs – is highly appreciated!!
You're on the right track with your theory: the behavior you're describing is how asynchronous data works with closures. You've experienced how this causes problems with returning the data you want. It's a very common question. In fact, I wrote a blog on this recently, and I recommend you check it out so you can apply the solution: incorporating closures into your functions. Here's what that looks like in the particular case you've shown:
func getAvailableProducts(completion: #escaping ([Product])-> Void) {
var products = [Product]()
var data: DataSnapshot = DataSnapshot()
self.ref.child("products").queryOrderedByKey().observeSingleEvent(of: .value) { (snapshot) in
data = snapshot
// do whatever you were planning on doing to return your data into products... probably something like
/*
for snap in snapshot.children.allObjects as? [DataSnapshot] {
let product = makeProduct(snap)
products.append(product)
}
*/
completion(products)
}
}
Then in viewWillAppear:
override func viewWillAppear(_ animated: Bool) {
FirebaseFactory().getAvailableProducts(){ productsArray in
// do something with your products
self.products = productsArray
// maybe reload data if you have a tableview
self.tableView.reloadData()
}
}
If I understand your question, you need to return the data after the event occurs, because is an async event
class FirebaseFactory {
var ref = Database.database().reference()
func getAvailableProducts() -> [Product] {
var products = [Product]()
var data: DataSnapshot = DataSnapshot()
self.ref.child("products").queryOrderedByKey().observeSingleEvent(of: .value) { (snapshot) in
data = snapshot
// 1st print statement
print("From within closure: \(data)")
// Process here the snapshot and insert the products in the array
return products
}
}
}

Firebase retrieving related data in swift

I'm new to Firebase. Not good at DB also.
I'm really hoping that people could give me advices about my DB design and retrieving data codes.
I designed the DB as below.
The comment have a createTs for ordering.But the content shouldn't ordered by create time. So I put a "index" key into contents info in the post.(I'm not sure if it is a good way)
About the data retrieving, I made a dataManager object to load data.
DataManger.swift
func loadPosts(completeBlock : ([Post]) -> Void ) {
ref.child("posts").observeEventType(.Value , withBlock: { snapshot in
var postList : [Post] = []
if snapshot.value is NSNull {
} else {
for post in snapshot.children {
let postSnap = post as! FIRDataSnapshot
let post = Post()
post.setValue(withSanpShot: postSnap)
post.commentList = []
for key in post.comments.keys {
self.loadPostComment(withKey: key, completeBlock: { (comment) in
post.commentList.append(comment)
})
}
post.contentList = []
for key in post.contents.keys {
self.loadPostContent(withKey: key, completeBlock: { (content) in
post.contentList.append(content)
})
}
postList.append(post)
}
}
completeBlock(postList)
})
}
func loadPostComment(withKey key: String, completeBlock:(Comment) -> Void) {
ref.child("post-comments").child(key).observeEventType(.Value, withBlock: { commentSnapShot in
let comment = Comment()
comment.setValue(withSanpShot: commentSnapShot)
completeBlock(comment)
})
}
func loadPostContent(withKey key: String, completeBlock:(PostContent) -> Void) {
ref.child("post-contents").child(key).observeEventType(.Value, withBlock: { contentSnapShot in
let content = PostContent()
content.setValue(withSanpShot: contentSnapShot)
completeBlock(content)
})
}
And struct of the Post.swift.
class Post: NSObject {
var postID : String
var authorID: String
var title: String
var createTS : NSNumber
var comments : [String : AnyObject]
var contents : [String : AnyObject]
var commentList : [Comment] {
didSet {
//TODO: add some closure to update view.Maybe also need sorting codes
print("commentList : \(commentList)")
}
}
var contentList : [PostContent] {
didSet {
//TODO: add some closure to update view.Maybe also need sorting codes
print("contentList : \(contentList)")
}
}
}
I'm not sure the work I'v done is the right way to using it.Although I could got the data I want.
Please give me advices. That will be really helpful to me. Thanks.