Parse iOS SDK: How to set user “online” status?

后端 未结 1 1793
甜味超标
甜味超标 2021-02-10 18:53

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 cod

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-10 19:49

    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).

    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);
        });
    });
    

    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).

    0 讨论(0)
提交回复
热议问题