firebase database - work with lists
2018-02-28 11:00
661 查看
Work with Lists of Data on iOS
Get a FIRDatabaseReference
To read or write data from the database, you need an instance ofFIRDatabaseReference:
SWIFT
OBJECTIVE-C
@property (strong, nonatomic) FIRDatabaseReference *ref;self.ref = [[FIRDatabase database] reference];Note: By default, read and write access to your database is restricted so only authenticated users can read or write data. To get started without setting up Authentication, you can configure your rules for public access. This does make your database open to anyone, even people not using your app, so be sure to restrict your database again when you set up authentication.
Reading and writing lists
Append to a list of data
Use thechildByAutoIdmethod to append data to a list in multiuser applications. The
childByAutoIdmethod generates a unique key every time a new child is added to the specified Firebase reference. By using these auto-generated keys for each new element in the list, several clients can add children to the same location at the same time without write conflicts. The unique key generated by
childByAutoIdis based on a timestamp, so list items are automatically ordered chronologically.You can use the reference to the new data returned by the
childByAutoIdmethod to get the value of the child's auto-generated key or set data for the child. Calling
getKeyon a
childByAutoIdreference returns the auto-generated key.You can use these auto-generated keys to simplify flattening your data structure. For more information, see the data fan-out example.
Listen for child events
Child events are triggered in response to specific operations that happen to the children of a node from an operation such as a new child added through thechildByAutoIdmethod or a child being updated through the
updateChildValuesmethod.
Event type | Typical usage |
---|---|
FIRDataEventTypeChildAdded | Retrieve lists of items or listen for additions to a list of items. This event is triggered once for each existing child and then again every time a new child is added to the specified path. The listener is passed a snapshot containing the new child's data. |
FIRDataEventTypeChildChanged | Listen for changes to the items in a list. This event is triggered any time a child node is modified. This includes any modifications to descendants of the child node. The snapshot passed to the event listener contains the updated data for the child. |
FIRDataEventTypeChildRemoved | Listen for items being removed from a list. This event is triggered when an immediate child is removed.The snapshot passed to the callback block contains the data for the removed child. |
FIRDataEventTypeChildMoved | Listen for changes to the order of items in an ordered list. This event is triggered whenever an update causes reordering of the child. It is used with data that is ordered by queryOrderedByChildor queryOrderedByValue. |
SWIFT
OBJECTIVE-C
// Listen for new comments in the Firebase database[_commentsRef
observeEventType:FIRDataEventTypeChildAdded
withBlock:^(FIRDataSnapshot *snapshot) {
[self.comments addObject:snapshot];
[self.tableView insertRowsAtIndexPaths:@[
[NSIndexPath indexPathForRow:self.comments.count - 1 inSection:kSectionComments]
]
withRowAnimation:UITableViewRowAnimationAutomatic];
}];
// Listen for deleted comments in the Firebase database
[_commentsRef
observeEventType:FIRDataEventTypeChildRemoved
withBlock:^(FIRDataSnapshot *snapshot) {
int index = [self indexOfMessage:snapshot];
[self.comments removeObjectAtIndex:index];
[self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:kSectionComments]]
withRowAnimation:UITableViewRowAnimationAutomatic];
}];
Listen for value events
While listening for child events is the recommended way to read lists of data, there are situations listening for value events on a list reference is useful.Attaching aFIRDataEventTypeValueobserver to a list of data will return the entire list of data as a single DataSnapshot, which you can then loop over to access individual children.Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
SWIFT
OBJECTIVE-C
[_commentsRefobserveEventType:FIRDataEventTypeValue
withBlock:^(FIRDataSnapshot *snapshot) {
// Loop over children
NSEnumerator *children = [snapshot children];
FIRDataSnapshot *child;
while (child = [children nextObject]) {
// ...
}
}];This pattern can be useful when you want to fetch all children of a list in a single operation, rather than listening for additional child added events.
Sorting and filtering data
You can use the Realtime DatabaseFIRDatabaseQueryclass to retrieve data sorted by key, by value, or by the value of a child. You can also filter the sorted result to a specific number of results or a range of keys or values.Note: Filtering and sorting can be expensive, especially when done on the client. If your app uses queries, define the
.indexOnrule to index those keys on the server and improve query performance as described in Indexing Your Data.
Sort data
To retrieve sorted data, start by specifying one of the order-by methods to determine how results are ordered:Method | Usage |
---|---|
queryOrderedByKey | Order results by child keys. |
queryOrderedByValue | Order results by child values. |
queryOrderedByChild | Order results by the value of a specified child key or nested child path. |
SWIFT
OBJECTIVE-C
// My top posts by number of starsFIRDatabaseQuery *myTopPostsQuery = [[[self.ref child:@"user-posts"]
child:[super getUid]]
queryOrderedByChild:@"starCount"];This query retrieves the user's posts from the path in the database based on their user ID, ordered by the number of stars each post has received. This technique of using IDs as index keys is called data fan out, you can read more about it in Structure Your Database.The call to the
queryOrderedByChildmethod specifies the child key to order the results by. In this example, posts are sorted by the value of the
"starCount"child in each post. Queries can also be ordered by nested children, in case you have data that looks like this:"posts": {
"ts-functions": {
"metrics": {
"views" : 1200000,
"likes" : 251000,
"shares": 1200,
},
"title" : "Why you should use TypeScript for writing Cloud Functions",
"author": "Doug",
},
"android-arch-3": {
"metrics": {
"views" : 900000,
"likes" : 117000,
"shares": 144,
},
"title" : "Using Android Architecture Components with Firebase Realtime Database (Part 3)",
"author": "Doug",
}
},In this case, we can order our list elements by values nested under the
metricskey by specifying the relative path to the nested child in our
queryOrderedByChildcall.
SWIFT
OBJECTIVE-C
FIRDatabaseQuery *postsByMostPopular = [[ref child:@"posts"] queryOrderedByChild:@"metrics/views"];For more information on how other data types are ordered, see How query data is ordered.
Filtering data
To filter data, you can combine any of the limit or range methods with an order-by method when constructing a query.Method | Usage |
---|---|
queryLimitedToFirst | Sets the maximum number of items to return from the beginning of the ordered list of results. |
queryLimitedToLast | Sets the maximum number of items to return from the end of the ordered list of results. |
queryStartingAtValue | Return items greater than or equal to the specified key or value, depending on the order-by method chosen. |
queryEndingAtValue | Return items less than or equal to the specified key or value, depending on the order-by method chosen. |
queryEqualToValue | Return items equal to the specified key or value, depending on the order-by method chosen. |
queryStartingAtValueand
queryEndingAtValuemethods to limit the results to a specified range of values.
Limit the number of results
You can use thequeryLimitedToFirstand
queryLimitedToLastmethods to set a maximum number of children to be synced for a given callback. For example, if you use
queryLimitedToFirstto set a limit of 100, you initially only receive up to 100
FIRDataEventTypeChildAddedcallbacks. If you have fewer than 100 items stored in your Firebase database, an
FIRDataEventTypeChildAddedcallback fires for each item.As items change, you receive
FIRDataEventTypeChildAddedcallbacks for items that enter the query and
FIRDataEventTypeChildRemovedcallbacks for items that drop out of it so that the total number stays at 100.The following example demonstrates how an example blogging app might retrieve a list of the 100 most recent posts by all users:
SWIFT
OBJECTIVE-C
// Last 100 posts, these are automatically the 100 most recent// due to sorting by push() keys
FIRDatabaseQuery *recentPostsQuery = [[self.ref child:@"posts"] queryLimitedToFirst:100];
Filter by key or value
You can usequeryStartingAtValue,
queryEndingAtValue, and
queryEqualToValueto choose arbitrary starting, ending, and equivalence points for queries. This can be useful for paginating data or finding items with children that have a specific value.
How query data is ordered
This section explains how data is sorted by each of the order-by methods in theFIRDatabaseQueryclass.
queryOrderedByKey
When using queryOrderedByKeyto sort your data, data is returned in ascending order by key.Children with a key that can be parsed as a 32-bit integer come first, sorted in ascending order.
Children with a string value as their key come next, sorted lexicographically in ascending order.
queryOrderedByValue
When using queryOrderedByValue, children are ordered by their value. The ordering criteria are the same as in
queryOrderedByChild, except the value of the node is used instead of the value of a specified child key.
queryOrderedByChild
When using queryOrderedByChild, data that contains the specified child key is ordered as follows:Children with a
nilvalue for the specified child key come first.
Children with a value of
falsefor the specified child key come next. If multiple children have a value of
false, they are sorted lexicographically by key.
Children with a value of
truefor the specified child key come next. If multiple children have a value of
true, they are sorted lexicographically by key.
Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key.
Strings come after numbers and are sorted lexicographically in ascending order. If multiple children have the same value for the specified child node, they are ordered lexicographically by key.
Objects come last and are sorted lexicographically by key in ascending order.
Detach listeners
Observers don't automatically stop syncing data when you leave aViewController. If an observer isn't properly removed, it continues to sync data to local memory. When an observer is no longer needed, remove it by passing the associated
FIRDatabaseHandleto the
removeObserverWithHandlemethod.When you add a callback block to a reference, a
FIRDatabaseHandleis returned. These handles can be used to remove the callback block.If multiple listeners have been added to a database reference, each listener is called when an event is raised. In order to stop syncing data at that location, you must remove all observers at a location by calling the
removeAllObserversmethod.Calling
removeObserverWithHandleor
removeAllObserverson a listener does not automatically remove listeners registered on its child nodes; you must also be keep track of those references or handles to remove them.
Next Steps
Learn how to structure dataStore data offline
相关文章推荐
- [React Native + Firebase] React Native: Real time database with Firebase -- setup & CRUD
- firebase database: scale with multiple databases
- firebase database: Extend realtime database with cloud functions
- [AngularFire2] Auth with Firebase auth -- email
- [AngularFire] Angular File Uploads to Firebase Storage with Angular control value accessor
- 拥抱Firebase,Firebase之Realtime Database。(含github源码),欢迎关注。
- firebase database read and write
- do A/B test with firebase remote config
- firestore vs firebase database
- 【Android 进阶:翻译】Get Started With Firebase for Android
- [Angular] Setup automated deployment with Angular, Travis and Firebase
- [Angular 2] Get start with Firebase
- understanding firebase database billing
- firebase database - offline access
- firebase database limit
- Android 集成FireBase Realtime DataBase实现聊天
- Custom Database Integration with Openfire 3.6.4
- best practice of data structure of firebase database
- Deploying OpenFire for IM (instant message) service (TCP/IP service) with database MySQL , client Spark on linux部署OpenFire IM 消息中间件服务
- understand firebase realtime database rules