Tom Testicool
Tom Testicool

Reputation: 563

Parse iOS SDK: How to set user "online" status?

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];

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"?

(please include method names)

Upvotes: 4

Views: 1841

Answers (1)

Timothy Walters
Timothy Walters

Reputation: 16874

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

Upvotes: 10

Related Questions