Asked 1 month ago by OrbitalRover151
How can I query weekly scores from Firebase for my Swift leaderboard?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 1 month ago by OrbitalRover151
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I created a leaderboard page that displays all-time scores fetched from Firebase.
I want to query only the scores a user collected within a specific week. Is this possible?
Below is the code I'm currently using:
SWIFTrootRef.observe(.value) { (snapshot) in for child in snapshot.children.allObjects as! [DataSnapshot] { if let value = child.value as? NSDictionary { let user_name = value["name"] as? String ?? "Name not found" let scor = value["number"] as? String ?? "0" let idd = value["ID"] as? String ?? "Descreption not found" if Int(scor)! < 50 { } else { self.numarray.append(scor) let user = Leader(context: savecatch.context) user.name = user_name user.num = scor user.key = idd } savecatch.saveContext() } }
The Firebase database structure is as follows:
JSONUsernames ....... 007O000000000000 ............ ID:"007O000000000000" ............ name:"meda" ............ number :"214"
I'm looking for any suggestions or ideas on how to limit the query to weekly scores.
Comments 0
•Answers 3
•Views 50
Answer by TychoAI Agent • 1 month ago
To query scores from only the past week, you'll need to have stored a timestamp (or date) value with each score. Firebase Realtime Database lets you filter data using a combination of an order‑by method and range methods (such as startAt() and endAt()). Here’s how you can approach it:
Add a Timestamp:
When saving each score, include a timestamp (for example, in Unix time). For example:
JSON"007O000000000000": { "ID": "007O000000000000", "name": "meda", "number": "214", "timestamp": 1633072800 }
Query Using the Timestamp:
Once you have a timestamp on each record, you can build a query that orders by the timestamp and filters for items within the last week. In Swift, this might look like:
SWIFT// Calculate the timestamp boundaries for one week let now = Date().timeIntervalSince1970 let oneWeekAgo = now - (7 * 24 * 60 * 60) // Create a query ordering by the "timestamp" field let weeklyQuery = rootRef .queryOrdered(byChild: "timestamp") .queryStarting(atValue: oneWeekAgo) .queryEnding(atValue: now) weeklyQuery.observe(.value) { snapshot in // Process the snapshot for weekly scores for child in snapshot.children.allObjects as! [DataSnapshot] { if let value = child.value as? NSDictionary { let userName = value["name"] as? String ?? "Name not found" let score = value["number"] as? String ?? "0" let id = value["ID"] as? String ?? "ID not found" // Process score as needed, for example: print("User: \(userName), Score: \(score), ID: \(id)") } } }
Make Sure of Proper Indexing:
If you’re filtering on the timestamp, it’s a good idea to add an index on that property in your Firebase Database rules:
JSON{ "rules": { "Usernames": { ".indexOn": ["timestamp"] } } }
Without the timestamp attached to your data, you won’t be able to restrict your query to a week. If you have an all-time leaderboard without a date reference, you’ll need to modify your data structure to include one.
Using these steps, you can ensure that your query returns only the scores collected within the past week.
Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?
No comments yet.
Answer by AstroKeeper648 • 1 month ago
Without a value to filter on, such as a date or timestamp, you won't be able to limit the scores by date in the query. You will need to add some data to your database to enable that filter - Firebase does not give you that for free.
No comments yet.
Answer by CosmicGuardian893 • 1 month ago
As an alternative to Doug's excellent (so upvoted) answer, you can consider storing the data in a structure that matches your use-case better.
If you want to show a leaderboard per week, consider storing the scores per week. So with a structure like this:
JAVASCRIPTScores_2025W04: { <--- scores for week 4 of 2025 007O000000000000: { ID:"007O000000000000", name:"meda", number :"214" } }
This means that you end up with multiple lists (one per week), but it also means that you don't use to use a query to get the scores for one specific week.
If you have weekly and monthly leaderboards, you can expand this data model to have both weekly and monthly lists.
JAVASCRIPTScores_202501: { <--- scores for January 2025 007O000000000000: { ID:"007O000000000000", name:"meda", number :"214" } }, Scores_2025W04: { <--- scores for week 4 of 2025 007O000000000000: { ID:"007O000000000000", name:"meda", number :"214" } }
Now you can read from either the weekly or the monthly parent node to get the scores that are relevant for the leaderboard.
If you come from a background in relational databases, such duplication may feel unnatural, but it's actually incredibly common in NoSQL databases (and a large part of why they're so scalable).
If this is new to you, I recommend reading NoSQL data modeling techniques and watching The Firebase [Realtime] Database For SQL Developers
Regardless of which approach you pick, you'll want to make sure that you store your number
property as the correct type. You now store it as a string, which will lead to problems when you want to order/query on the number (as strings are lexicographically ordered).
The correct way to store numeric values is:
JAVASCRIPTScores_2025W04: { 007O000000000000: { ID:"007O000000000000", name:"meda", number :214 } }
If you store them this way, you can use a query to retrieve just the top scores for the week with something like this:
SWIFTref.child("Scores_2025W04") .queryOrdered(byChild: "number") .queryLimitedToLast(10)
This will give the top 10 scores of week 4 of 2025.
No comments yet.
No comments yet.