Swift - Parse - Check if username is taken

大兔子大兔子 提交于 2019-12-04 18:22:59

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")
    }
}
pbush25

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)
            }
        }
    }

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")


            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!