J.M J.M - 8 days ago 4x
Swift Question

How to check for user info with PFQuery

When a user signs up he/she is redirected to another view controller where they need to verify their phone number. I tried setting up a PFQuery to retrieve the user's code from Parse, and see if it matches with what was written in the verification text field, however, it always results in the user being redirected to the main view controller whether the code entered is right or wrong. I've also tried doing so with objectForKey (currentUser) and the query

if phoneCode != currentUser
, however the result is the same. What I am trying to do is check if the code entered is the correct one, and redirect the user to another view controller based on the response.

@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.")
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
//let loginVC = self.storyboard?.instantiateViewControllerWithIdentifier("signInPage")
//self.navigationController?.pushViewController(loginVC!, animated: true)



In your first if statement, you are telling the server that if there is an error finding objects OR the query found some objects, then display the alert. But given that the user enters a wrong code, the query will return an empty array(note that it won't return nil, it's an empty array), but there won't be any errors, thus the else block is executed.

and since your "phoneVerification" is a Number, we need to covert the codeTextField.textinto NSNumber:

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

you can change your first if statement to :

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