我在posts
数据库中有一个Firebase
表,其结构如下:
"posts": {
"111" : {
"pName" : "ABC",
"pMessage" : "Hello",
"pOrder" : 555
},
"112" : {
"pName" : "BCD",
"pMessage" : "ELLO",
"pOrder" : 444
},
"113" : {
"pName" : "A",
"pMessage" : "Ollo",
"pOrder" : 555
}.
.....
}
posts
表中有相当多的记录。所以,我已经实现了分页,一次从Firebase
获取20条记录。我已将observeEventType
设置为FIRDataEventType.Value
,以便它会收听posts
中的所有活动。以下是分页代码:
/*
retrieve current set of posts sorted by pOrder of posts
*/
func retrievePost(offset: NSNumber, completion: (result: AnyObject?, error: NSError?)->()){
// As this method is called from viewDidLoad and fetches 20 records at first.
// Later when user scrolls down to bottom, its called again
let postsRef = ref.child(kDBPostRef)
var startingValue:AnyObject?
// starting value will be nil when this method is called from viewDidLoad as the offset is not set
if offset == 0{
startingValue = nil
}
else{
startingValue = offset
}
// sort records by pOrder fetch offset+1 records
self.refHandler = postsRef.queryOrderedByChild("pOrder").queryStartingAtValue(startingValue).queryLimitedToFirst(kPostLimit + 1).observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
// flag is for setting the last record/ 21st as offset
var flag = 0
var tempPost:[Post] = []
// iterate over children and add to tempPost
for item in snapshot.children {
// check for offet, the last row(21st) is offset ; Do not add last element in the main table list
flag += 1
if flag == 21 {
// this row is offset
self.kOffsetKey = item.value?["pOrder"] as! NSNumber
continue
}
// create Post object
let post = Post(snapshot: item as! FIRDataSnapshot)
// append to tempPost
tempPost.append(post)
}
// return to the closure
completion(result:tempPost, error:nil)
})
}
这里我每次调用此方法时都会设置offset
以获取接下来的20条记录。
现在,假设我更新了帖子(通过更新pMessage
),对于该更新,引用处理程序再次调用此特定方法(retrievePost
)。为了同步数据,我维护一个offsetDict
字典,它将记录特定数据范围的偏移量:
offsetDict:[Range(0-20): "nil", Range(21-40):"444", Range(41-60):"666"]
因此,当更新活动调用retrievePost
时,将从此字典中选择偏移量,否则偏移量将由正常检索活动(self.kOffsetKey
)设置。
所以我的问题是:
这是实现此特定功能的正确方法吗?
现在,假设我通过后端服务向帖子添加了更多新记录,在这种情况下,我的refHandler
将如何处理获取新记录并自动将其显示到应用程序{{1}那种事情?