解析iOS SDK:如何设置用户“在线”状态? [英] Parse iOS SDK: How to set user "online" status?

查看:106
本文介绍了解析iOS SDK:如何设置用户“在线”状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景=我有一个应用程序,允许用户登录并查看在线的其他用户。为了设置每个用户的在线状态,我相信我应该设置代码......

Scenario = I have an app that allows users to log in and view other users who are also "online". In order to set each user's online status I believe that I should set the code...

[PFUser currentUser] setObject:[NSNumber numberWithBool:YES] forKey:@"isOnline"];
[[PFUser currentUser] saveInBackground];

在用户使用应用程序时的某些时间。可能是appDelegate,但我不确定。

at certain times in the application when the user uses the app. Probably the appDelegate but I'm not sure.

(如果这不正确那请纠正我)

(if this is not correct then please correct me)

问题=应在应用程序中设置此代码的位置,以便始终跟踪用户何时在线以及何时离线?

Question = Where should this code be set inside the application so that it always keeps track of when a user is "online" and when they are "offline"?

(请包含方法名称)

推荐答案

处理此问题的最可靠方法是创建名为的列lastActive 类型为Date,然后创建一个Cloud Code函数来更新服务器时间(因此时钟差异不是问题)。

The most reliable way to handle this is to create a column named lastActive of type Date, then create a Cloud Code function to update this with the server time (so clock differences isn't an issue).

然后为了让在线用户只有另一个云函数进行查询,其中 lastActive 比现在更大 - 某个时间窗口就像2分钟。

Then to get "online" users just have another Cloud Function that does a query where lastActive is greater than now - some time window like 2 minutes.

var moment = require("moment");

Parse.Cloud.define("registerActivity", function(request, response) {
    var user = request.user;
    user.set("lastActive", new Date());
    user.save().then(function (user) {
        response.success();
    }, function (error) {
        console.log(error);
        response.error(error);
    });
});

Parse.Cloud.define("getOnlineUsers", function(request, response) {
    var userQuery = new Parse.Query(Parse.User);
    var activeSince = moment().subtract("minutes", 2).toDate();
    userQuery.greaterThan("lastActive", activeSince);
    userQuery.find().then(function (users) {
        response.success(users);
    }, function (error) {
        response.error(error);
    });
});

您的客户需要调用 registerActivity 云功能每1.5分钟允许一些重叠,因此如果用户的互联网有点慢,用户似乎不会离线。

Your client will want to call the registerActivity Cloud Function every 1.5 minutes to allow some overlap so users don't appear to go offline if their internet is a bit slow.

当然,您可以将时间窗口调整为适合您的需求。您还可以添加过滤返回用户的功能(例如,仅限在线朋友)。

Of course you can adjust the time windows to suit your needs. You could also add the ability to filter which users are returned (e.g. online friends only).

这篇关于解析iOS SDK:如何设置用户“在线”状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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