1

I am trying to create a function that takes a username as a parameter and checks to see if that username is taken (by comparing it to other PFUsers in the Parse database. This function is in my view controller class. (I know there are similar questions to this but they do not provide quality answers and are more general than this or are not in Swift).

func usernameIsTaken(username: String) -> Bool {

    //bool to see if username is taken
    var isTaken: Bool = false

    //access PFUsers
    var query : PFQuery = PFUser.query()!
    query.whereKey("User",  equalTo: username)

    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) in

        if error == nil {
            if (objects!.count > 0){
                isTaken = true
                println("username is taken")
            } else {
                println("Username is available. ")
            }
        } else {
            println("error")
        }
    }

    return isTaken

}

The problem is that the condition in the if statement is always false so "Username is available" always prints in the console even if the username is taken."Username is taken" is never printed even when the username is taken. What should I put in the nested if statement to check if the username matches another PFUser?

rici
  • 234,347
  • 28
  • 237
  • 341
TheCodeComposer
  • 725
  • 5
  • 17

3 Answers3

3

You are querying for User (class) key, but you need to query for a specific key, for example email.

// First get user's inputted email
let enteredEmailAddress = "sample@gmail.com"

// Then query and compare
var query = PFQuery(className: "_User")
query.whereKey("email", equalTo: enteredEmailAddress)
query.findObjectsInBackgroundWithBlock {
    (objects: [AnyObject]?, error: NSError?) in
    if error == nil {
        if (objects!.count > 0){
            isTaken = true
            println("username is taken")
        } else {
            println("Username is available. ")
        }
    } else {
        println("error")
    }
}
Klevison
  • 3,342
  • 2
  • 19
  • 32
  • I'm getting an error that says "cannot invoke findObjectsInBackgroundWithBlock with an argument list of type AnyObject, NSError -> Void" Do you know what this means? – TheCodeComposer Jul 29 '15 at 00:12
  • That eliminated the previous error but not it's giving me this new error "could not find member updatedAt". Using the optionals seems to work, but now that println statement is faulty. I'm guessing you're not getting any of these errors. I'm on Xcode 6.4 by the way. – TheCodeComposer Jul 29 '15 at 00:19
  • My example is too generic. You need to unterstande Parse Framework. Only you need is adapt your code with my code. This is my last update. – Klevison Jul 29 '15 at 00:23
1

Just thought I would throw this out there, since this doesn't seem to be well known by people as I've answered a similar question before. Parse does this kind of checking for the user class automatically. If you're trying to create a new user with any of the default fields duplicated in Parse i.e username, email, etc, then Parse will not allow user signup. This is done automatically, with you having to do nothing, except for present the error so the user knows why they weren't able to sign up successfully. An example of signing a user up that checks for username email etc duplicates follows below:

user.signUpInBackgroundWithBlock {
            (succeeded: Bool, signupError: NSError?)
            -> Void in

            if signupError == nil {
                //present new controller
                println("Signed up")

            }
            else {
                if let errorString = signupError!.userInfo?["error"] as? NSString
                {
                    error = errorString as String
                }
                else {
                    error = "We're sorry, an error ocured! Please try again."
                }

                self.displayAlert("Could not sign up", error: error)
            }
        }
    }
Community
  • 1
  • 1
pbush25
  • 5,228
  • 2
  • 26
  • 35
  • This is more so for signing up instead of checking if the username is already taken. Thanks for the answer though, it's great info. Cheers. – TheCodeComposer Jul 29 '15 at 03:59
  • You're right, sorry I just figured that was the use case in which you would need to know if a username already exists. Sorry for assuming! – pbush25 Jul 29 '15 at 04:01
0

Check the error code. Last time I did this, code 202 = Username Taken, code 203 = e-mail taken.

            if signupError == nil {

                print("User \(user.username!) signed up OK!")


            } else if signupError?.code == 202 {

                print("Username taken. Please select another")


            } else if signupError?.code == 203 {

                print("e-Mail taken. Please select another")


            }
Ian F
  • 59
  • 1
  • 4