Don't want to download all objects - swift

I'm having a hard time understanding how I should structure my iOS app with regards to how Firebase works. I've got a few thousand users with my current implementation (not using firebase currently), but using .childAdded will give me all of the items in my db (of course to start with) but I'm trying to build something with .childAdded that allows me to say download the first 20 items, then as they scroll the tableview it downloads the next 20 items. My users post a lot of photos and their feed would be blown up with the amount of posts that .childAdded returns.
Thoughts on what to do?

This may help you better understand how to convert Firebase Queries into equivalent SQL Queries.
https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html#paginate
// fetch page 2 of messages
new Firebase("https://examples-sql-queries.firebaseio.com/messages")
.startAt(2) // assumes the priority is the page number
.endAt(2)
.once('value', function(snap) {
console.log('messages in range', snap.val());
});

Here you can see the documentation that Explains Queries
You can go to the part that says limitToFirst.
For Example this says to limit to last 10:
var rootRef = firebase.database.ref();
var usersRef = rootRef.child("users");
var usersQuery = usersRef.limitToLast(10);
usersQuery.isEqual(usersRef); // false
usersQuery.isEqual(usersRef.limitToLast(10)); // true
usersQuery.isEqual(rootRef.limitToLast(10)); // false
usersQuery.isEqual(usersRef.orderByKey().limitToLast(10)); // false

Related

Anybody know how to make a search in a app that searches the database? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am working on an app in swift and need help. I am trying to have a search object on the screen and when you type letters it will bring a result from the realtime database using firebase. Please help. I don't know how I can code that. Please Please Please Help.
You have to be a bit more specific about what exactly is it that you are trying to do. Firstly - what technologies are you using? JavaScript? What framewroks? React? Angular? Vuejs? Vanilla JavaScript? Is it a restful application you are doing or server rendered?
Depending on your answers to the above questions the code can vary greatly. Here I can give you a general solution though:
first create the search box and a button with an action that sends a request (mostly HTML)
that request can be an AJAX GET request to look for results in the database, based on a certain search keyword. I recommend a library called axios to help you with that. (sending and resolving promises with JavaScript)
handle the response of that request and if the response is valid (with status 200) then update your search results. (mostly JavaScript)
I just did this a few weeks ago for my app you are in luck! I am using swift programming language btw.
So according to firebase you should not use firebase to search for documents in the database. Firebase Documentation on this.. Instead you should use something else like "Algolia", "Elastic", or "typeSense". I chose to use Algolia and it took me about a day to implementing my app. Super easy.
But if you really want to use firebase (which is not recommended) you could use this:
func loadPost(lastDoc: QueryDocumentSnapshot?, completion: #escaping (QueryDocumentSnapshot?) -> Void) {
let db: Query
// Check to see if previous documents have been loaded or not.
if let lastDoc = lastDoc {
db = Firestore.firestore().collection("collection name")
.order(by: "document name you are wanting to get. example: postTitle, username, date, etc")
// Amount of documents you want to retrieve from your colleciton
.limit(to: 10)
// Check certain conditions that you want to retrieve.
// In this example we are only retrieving the posts that have 100 reports or greater.
.whereField("reportCount", isGreaterThan: 100)
// Start after the previous loaded document so we don't waste data by reloading documents that have already been loaded.
.start(afterDocument: lastDoc)
// If there are no previous loaded documents then you just start from the beginning of your collection colleciton.
} else {
db = Firestore.firestore().collection("posts")
.order(by: "document name", descending: true)
.limit(to: 10)
.whereField("document name", isGreaterThan: 100)
}
// finally get the documents you want from firebase
db.getDocuments { query, error in
// Check for errors
if let query = query, error == nil {
// Not really sure why you need a dispatchgroup, but its kind of like a completionHandler for a for loop.
let group = DispatchGroup()
for doc in query.documents {
group.enter()
// run the code you need to run:
// After the code is finished running you need to call group.leave()
group.leave()
}
// After the for loop is completely done call group.notify which is basically like a completionHandler
group.notify(queue: .main) {
// notify whatever needs to be notified.
// finally insert the last document loaded so when we need to load data again it only loads documents that have not been loaded.
completion(query.documents.last)
}
} else {
completion(nil)
}
}
}

fire base custom search is stuck

I am doing firebase programming with iOS.
I could do normal searching with code like below
ref.child("Users").queryOrderedByChild("name").queryStartingAtValue(text).observeEventType(.Value, withBlock: { snapshot in
for u in snapshot.children{
print(user.name)
}
})
but i am confused, as i want to find people near me. every record has lat long values, where in the server i would put code to evaluate distance between my current location and friends location and filter them ? I dont want to loop through all items in above for block (Client side)
Also, can i write server code to make services hosted in firebase ? what is the recommended way to get data from big server like redshift ?
Is firebase really drag-drop development ? i did not find anything of that sort in firebase documentation ! firbase-ui is open source, but it gives obj c code and no drag and drop ! request answer please

Possible to get latest data with observeSingleEvent + persistence enabled?

I am trying to get some data from firebase. Any idea how can I get the latest data (not from cache) when I have persistence enabled? I tried keepSynced; I still get stale data. Is this the correct usage?
userRef = FIRDatabase.database().reference().child("<path>")
userRef.keepSynced(true)
userRef.observeSingleEvent(of: .value, with: { snapshot in
...stale data here...
})
Or the only option is to use observe instead of observeSingleEvent? I don't like the fact that with observe I get the cache data first, and then the event triggers a second time with data from the server. So with observe, when I navigate to this screen, first I see a blank table, then I see the table with stale data, and then I see the table with latest data.
Thanks.
EDIT:
https://stackoverflow.com/a/34487195/1373592 -
This post says keeySynced should work. But it's not working for me. I would like to know if I am doing something wrong.
I retrieve some explanation, I think it might help you in your case :
ObserveSingleEventType with keepSycned will not work if the Firebase
connection cannot be established on time. This is especially true
during appLaunch or in the appDelegate where there is a delay in the
Firebase connection and the cached result is given instead. It will
also not work at times if persistence is enabled and
observeSingleEvent might give the cached data first. In situations
like these, a continuous ObserveEventType is preferred and should be
used if you absolutely need fresh data.
I think you don't have the choice to use a continuous listener. But to avoid performance issues why you don't remove yourself your listeners when you don't it anymore.
Here is an example on how to ALWAYS get latest data from firebase when persistence is turned on. Use observe event, keepSynced on your ref and terminate listener if you don't want to keep it always. After several trials, I came up with this and it is working.
func readFromFB() {
let refHandle: DatabaseHandle?
let ref: DatabaseReference? = firebase.child(nodeName)
ref?.keepSynced(true)
refHandle = ref!.observe(.value, with:
{ snapshot in
if snapshot.exists() {
for item in ((snapshot.value as! NSDictionary).allValues as Array) {
//do whatever tasks
}
}
})
if let rf = ref {
rf.removeObserver(withHandle: refHandle!)
}
}

Data from Firebase undefined in React

I'm playing with Firebase as an alternative to a local Mongo store, for the time being.
I've followed various tutorials, however they are all for older versions of ES6. I've tried to tweak them to v14 and ES6 but, well, no errors but no data!
Some code:
var Rebase = require('re-base');
var base = Rebase.createClass('https://reactathon.firebaseio.com/days');
...
componentDidMount() {
console.log('ExampleComponent Mounted');
base.bindToState('days', {
context: this,
state: 'days',
asArray: true
});
console.log(this.state.days[0]);
}
The console simply logs undefined. I've tried the base URL with and without /days. I've tried getting the data as an object instead of an array. I have a feeling I'm simply pointing at the wrong thing.
Any thoughts?
Cheers.
bindToState is an asynchronous method so it's going to take some time to set up that listener. You're logging before the listener has been set up. As Jacob mentioned in his comment, move your log to your render method and then once your state is bound to Firebase your component will re render and you should see your data.

ResearchKit: How to get pedometer data (step count specifically) from ORKOrderedTask.fitnessCheckTaskWithIdentifier result

I added the ORKOrderedTask.fitnessCheckTaskWithIdentifier Task and it renders find in the UI. But unlike other simpler tasks containing scale/choice/date questions, I was not able to find the exact way to read the sensor data collected via ORKOrderedTask.fitnessCheckTaskWithIdentifier.
I have used the following:
private var walkingTask : ORKTask {
return ORKOrderedTask.fitnessCheckTaskWithIdentifier("shortWalkTask", intendedUseDescription: "Take a short walk", walkDuration: 10, restDuration: 5, options: nil)
}
upon task completion the task view controller delegate below is hit.
//ORKTaskViewControllerDelegate
func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason reason: ORKTaskViewControllerFinishReason, error: NSError?)
is there a way to drill down into the result object contained in task view controller (taskViewController.result) to get the step count? Or will i have to go through health kit or something and then query the required observation? Request help from anyone who has used this task before and can provide some input on how to fetch the pedometer data (step count specifically) for the duration the task was active?
I'm using swift.
The step count is not reflected in the result objects per se. Instead, one of the child ORKFileResult objects, generated from the pedometer recorder, will contain the pedometer records queried from CoreMotion, serialized to JSON.
However, exposing the step count on a result object, sounds like a useful extension / improvement, and we should see if it generalizes to other recorders too. Please open an issue on GitHub and we will see what we can do!