关于Swift:如何使用PFQuery检查用户信息

How to check for user info with PFQuery

当用户注册时,他/她将被重定向到另一个需要验证其电话号码的视图控制器。我尝试设置一个PFQuery来从Parse中检索用户的代码,并查看它是否与验证文本字段中编写的代码匹配,但是,它总是导致用户被重定向到主视图控制器,无论输入的代码是否正确或错。我也尝试使用objectForKey(currentUser)和查询if phoneCode != currentUser这样做,但是结果是相同的。我正在尝试做的是检查输入的代码是否正确,然后根据响应将用户重定向到另一个视图控制器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@IBAction func submitCodeTapped(sender: AnyObject) {
    let currentUser = PFUser.currentUser()?.objectForKey("phoneVerification") as? NSValue
    let code = codeTextField.text
    let query = PFQuery(className:"User")
    let phoneCode = query.whereKey("phoneVerification", equalTo: code!)
    query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
        if error != nil || objects != nil {
        //if phoneCode != currentUser{
            self.displayAlert2("Wrong Code", message:"This is not the code you were sent.")
        }else{
            let myUser:PFUser = PFUser.currentUser()!
            myUser.setObject(true, forKey:"phoneVerified")
            myUser.saveInBackgroundWithBlock { (success, error) -> Void in
                if error == nil{
                    print("Successfully set the object.")
                    self.displayAlert("Great!", message:"Your phone number has been verified!", error: nil)
                    let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                    appDelegate.buildUserInterface()
                }else{
                    //let loginVC = self.storyboard?.instantiateViewControllerWithIdentifier("signInPage")
                    //self.navigationController?.pushViewController(loginVC!, animated: true)
                    print("Erreur")

                }
            }
        }
    })
}


在您的第一个if语句中,您告诉服务器,如果发现对象时出错,或者查询中找到了一些对象,则显示警报。但是假设用户输入了错误的代码,查询将返回一个空数组(请注意,它不会返回nil,它是一个空数组),但是不会有任何错误,因此else块被执行。

,并且由于您的" phoneVerification "是一个数字,因此我们需要将codeTextField.text转换为NSNumber:

1
2
3
let code = NSNumber(value:Int(codeTextField.text)!)
let query = PFQuery(className:"_User")
query.whereKey("phoneVerification", equalTo: code!)

您可以将第一个if语句更改为:

1
2
3
if ((error != nil && error! as! Bool) || objects?.count == 0) {
    //handle the error here.
}


更改

1
2
let query = PFQuery(className:"User")
let phoneCode = query.whereKey("phoneVerification", equalTo: code!)

1
2
let query = PFQuery(className:"_User")
query.whereKey("phoneVerification", equalTo: code!)

如果要使用查询来获取用户,则用户类的名称为_User。这就是为什么在您的代码中始终获取对象为nil的原因,因此转向else语句。

此外,我建议您打印对象并查看得到的内容。