1

我正在尝试使用 Parse 独占我的所有用户会话,这意味着如果用户已经在某个位置的某个设备上登录,如果另一个设备使用相同的凭据登录,我希望之前的会话是终止,当然带有警报视图的消息。有点像旧的 AOL 即时消息格式。我认为这个动作的代码应该写在登录逻辑中,所以我在我的登录“成功”代码中写了这个:

 PFUser.logInWithUsernameInBackground(userName, password: passWord) {
        (user, error: NSError?) -> Void in
        if user != nil || error == nil {
            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("loginSuccess", sender: self)

                 PFCloud.callFunctionInBackground("currentUser", withParameters: ["PFUser":"currentUser"])
                    //..... Get other currentUser session tokens and destroy them

            }

        } else {

那可能不是正确的云代码调用,但您明白了。当用户在另一台设备上再次登录时,我想抓取其他会话并终止它们。有谁知道快速提出这个请求的正确方法?

4

1 回答 1

2

我口吃很快,但我想我可以用几乎很快的语速回答。关键思想是只有在云表示可以之后才开始成功继续。这就是我认为你想要的:

PFUser.logInWithUsernameInBackground(userName, password: passWord) {
    (user, error: NSError?) -> Void in
    if (user != nil) {
        // don't do the segue until we know it's unique login
        // pass no params to the cloud in swift (not sure if [] is the way to say that)
        PFCloud.callFunctionInBackground("isLoginRedundant", withParameters: []) {
            (response: AnyObject?, error: NSError?) -> Void in
            let dictionary = response as! [String:Bool]
            var isRedundant : Bool
            isRedundant = dictionary["isRedundant"]!
            if (isRedundant) {
                // I think you can adequately undo everything about the login by logging out
                PFUser.logOutInBackgroundWithBlock() { (error: NSError?) -> Void in
                    // update the UI to say, login rejected because you're logged in elsewhere
                    // maybe do a segue here?
                }
            } else {
                // good login and non-redundant, do the segue
                self.performSegueWithIdentifier("loginSuccess", sender: self)
            }
        }
    } else {
        // login failed for typical reasons, update the UI
    }
} 

请不要对 swift 语法太认真。这个想法是将segue嵌套在完成处理程序中,以知道您需要在启动它之前执行它。另外,请注意,完成处理程序中 main_queue 上的显式放置是不必要的。SDK 在主程序上运行这些块。

一个简单的检查来确定用户的会话是否是多余的(不是唯一的)看起来像这样......

Parse.Cloud.define("isLoginRedundant", function(request, response) {
    var sessionQuery = new Parse.Query(Parse.Session);
    sessionQuery.equalTo("user", request.user);
    sessionQuery.find().then(function(sessions) {
        response.success( { isRedundant: sessions.length>1 } );
    }, function(error) {
        response.error(error);
    });
});
于 2015-08-27T19:31:47.423 回答