我正在尝试使用Parse独占进行所有用户会话,这意味着如果用户已经登录某个位置的某个设备,如果另一个设备使用相同的凭据登录,我想要前一个会话(s )终止,当然还有一个警报视图的消息。有点像旧的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 {
这可能不是正确的云代码调用,但你明白了。当用户再次在另一台设备上登录时,我想抓住其他会话并终止它们。有没有人知道在swift中提出这个请求的正确方法?
答案 0 :(得分: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
}
}
请不要过于认真地对待快速语法。我们的想法是将segue嵌套在完成处理程序中,以便知道在启动它之前需要执行它。另请注意,完成处理程序中main_queue上的显式放置是不必要的。 SDK在main上运行这些块。
确定用户会话是否冗余(非唯一)的简单检查看起来像这样......
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);
});
});