Asked 1 month ago by GalacticScholar516
How can I query weekly scores from my Firebase leaderboard in Swift?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 1 month ago by GalacticScholar516
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I built a leaderboard page that fetches all‑time scores from Firebase.
I now want to query only the scores a user collected within a specific week. Is this possible?
The code I'm currently using is:
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 is structured like this:
JSONUsernames ....... 007O000000000000 ............ ID:"007O000000000000" ............ name:"meda" ............ number :"214"
Any ideas or suggestions on how I can achieve querying just the scores for a week?
Comments 0
•Answers 3
•Views 51
Answer by TychoAI Agent • 1 month ago
To filter scores within a specific date range (such as a week), you'll need to store a timestamp (for example, a Unix epoch value) with each score entry in your database. Once each entry has a timestamp, you can query for items within a week by using the range methods (StartAt and EndAt) together with an order‑by method.
Add a Timestamp Field
When saving a new score, include a "timestamp" field representing when the score was recorded. For example:
SWIFTlet scoreData: [String: Any] = [ "ID": "007O000000000000", "name": "meda", "number": "214", "timestamp": Date().timeIntervalSince1970 // Unix epoch time ] rootRef.child("Usernames").childByAutoId().setValue(scoreData)
Compute the Start and End of the Week
Determine the Unix timestamp for the beginning and end of the week you’re interested in. For example:
SWIFT// This is just an example; adjust as needed for your regional calendar. let calendar = Calendar.current let now = Date() let startOfWeek = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: now))! let endOfWeek = calendar.date(byAdding: .day, value: 7, to: startOfWeek)! let startTimestamp = startOfWeek.timeIntervalSince1970 let endTimestamp = endOfWeek.timeIntervalSince1970
Query Scores for the Week
Use Firebase’s query methods to filter based on the timestamp field:
SWIFTlet weekQuery = rootRef .child("Usernames") .queryOrdered(byChild: "timestamp") .queryStarting(atValue: startTimestamp) .queryEnding(atValue: endTimestamp) weekQuery.observe(.value) { snapshot in 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 only those scores you actually need if let intScore = Int(score), intScore >= 50 { // Add score to the array, save to Core Data, etc. } } } }
Data Structure:
Your current database entry does not include date information. Without storing a timestamp along with your data, Firebase won’t be able to filter by date.
Query Methods:
Use queryOrdered(byChild:)
to order the data by the timestamp and then use queryStarting(atValue:)
and queryEnding(atValue:)
to fetch only those scores within the specified week.
By adding the timestamp field and using these query methods, you can successfully fetch only those scores from Firebase that were recorded within a 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 PlanetaryResearcher569 • 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 MeteorRover666 • 1 month ago
As an alternative to Doug's excellent (so upvoted) answer, you can consider storing the data in a structure that matches you use-case better.
If you want to show a leaderboard per week, consider storing the scores per week. So with a structure like this:
JSONScores_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.
JSONScores_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:
JSONScores_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.