如何跟踪某个项目的当前观看者数量? [英] How can I track the current number of viewers of an item?

查看:75
本文介绍了如何跟踪某个项目的当前观看者数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iPhone应用程序,我想在其中显示有多少人正在浏览这样的项目:

I have an iPhone app, where I want to show how many people are currently viewing an item as such:

我是通过在人们进入视图时运行此事务来完成此操作的(以下为Rubymotion代码,但功能与Firebase iOS SDK完全一样):

I'm doing that by running this transaction when people enter a view (Rubymotion code below, but functions exactly like the Firebase iOS SDK):

listing_reference[:listings][self.id][:viewing_amount].transaction do |data|
  data.value = data.value.to_i + 1
  FTransactionResult.successWithValue(data)
end

当他们退出视图时:

listing_reference[:listings][self.id][:viewing_amount].transaction do |data|
  data.value = data.value.to_i + -
  FTransactionResult.successWithValue(data)
end

在大多数情况下,它都能正常工作,但有时会出错.应用程序崩溃,人们失去了连接或类似的东西.

It works fine most of the time, but sometimes things go wrong. The app crashes, people loose connectivity or similar things.

我一直在寻找"onDisconnect"来解决此问题-

I've been looking at "onDisconnect" to solve this - https://firebase.google.com/docs/reference/ios/firebasedatabase/interface_f_i_r_database_reference#method-detail - but from what I can see, there's no "inDisconnectRunTransaction".

无论如何我如何确保清单上的观看量递减?

How can I make sure that the viewing amount on the listing gets decremented no matter what?

推荐答案

Firebase数据库事务作为比较并设置操作运行:给定节点的当前值,您的代码将指定新值.这要求客户端和服务器之间至少有一个往返,这意味着它本质上不适合onDisconnect()操作.

A Firebase Database transaction runs as a compare-and-set operation: given the current value of a node, your code specifies the new value. This requires at least one round-trip between the client and server, which means that it is inherently unsuitable for onDisconnect() operations.

onDisconnect()处理程序是一个简单的set()操作:您指定在附加处理程序时,当服务器检测到客户端已断开连接时(干净地或在您遇到问题的情况下)时要执行的写操作不由自主地).

The onDisconnect() handler is instead a simple set() operation: you specify when you attach the handler, what write operation you want to happen when the servers detects that the client has disconnected (either cleanly or as in your problem case involuntarily).

解决方案是(使用NoSQL数据库通常是这种情况)使用可以优雅地处理这种情况的数据模型.在您的情况下,似乎最自然的是不存储观看者的 count ,而是存储每个观看者的uid:

The solution is (as is often the case with NoSQL databases) to use a data model that deals with the situation gracefully. In your case it seems most natural to not store the count of viewers, but instead the uid of each viewer:

itemViewers
  $itemId
    uid_1: true
    uid_2: true
    uid_3: true

现在,您可以通过一个简单的value侦听器获得观看者的数量:

Now you can get the number of viewers with a simple value listener:

ref.child('itemViewers').child(itemId).on('value', function(snapshot) {
  console.log(snapshot.numChildren());
});

并使用以下onDisconnect()进行清理:

ref.child('itemViewers').child(itemId).child(authData.uid).remove();

这两个代码段均使用JavaScript语法,因为我只注意到键入它们后才使用Swift.

这篇关于如何跟踪某个项目的当前观看者数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆