How to check UserName taken in parse Xcode - ios

I'm trying to check if username is already taken in parse or not, but seems don't work with my code, can you please what i'm doing wrong on it
Thanks
func usernameIsTaken(userName: String) -> Bool {
let userName = userNameTextField.text
let myUser: PFUser = PFUser.currentUser()!
//bool to see if username is taken
var isTaken : Bool = false
//access PFUsers
let query = PFUser.query()
query!.whereKey("username", equalTo: userName!)
query!.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]? , error : NSError? ) in
if error == nil {
if (objects!.count > 0) {
isTaken = true
print("username is taken")
} else {
print("Username is available. ")
}
} else {
print("error")
}
}
return isTaken
}

For one, you can attempt to sign the user up and Parse will return an error code of 202 if the username has already been taken.
http://parse.com/docs/dotnet/api/html/T_Parse_ParseException_ErrorCode.htm
If this isn't your intended use, to query the User table, use PFUser.query to construct a query instead.

Try this :
query.findObjectsInBackgroundWithBlock({ (object: [PFObject]?,error: NSError?) -> Void in
if error == nil {
}
})
With that being said if your only Interested in the count parse introduced a new method similar to findObjectsInBackground but does exactly what you are looking for, the method is called countObjectsInBackground
You can call this method after you define your query.
like so
query.countObjectsInBackgroundWithBlock { (count: Int32,error: NSError?) -> Void in
if error == nil {
//code here
}
Hope this helps

Related

Check if PFObject is nil

I want to check if a PFObject is nil
I retrieve the object
var userLibrary: PFObject?
func getUserLibrary(user: PFUser) {
self.libraryQuery = PFQuery(className: "Library")
self.libraryQuery?.whereKey("owner", equalTo: user)
self.libraryQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if objects!.count > 0 {
self.userLibrary = objects![0]
} else {
print(self.userLibrary)
}
}
})
}
The last line with the print statement prints out nil.
However when I check :
if userLibrary != nil {
}
Xcode tells me
Binary operator '!=' cannot be applied to operands of type 'PFObject' and 'NilLiteralConvertible'
How do I fix this ?
I'm not 100% sure that this will work, but did you try.
if let lib = userLibrary {
//do whatever
}
Let me know.
Also, if you are just using the first object of your query. It would better to use getFirstObjectInBackground

Passing objectId from viewDidLoad to another function using Parse method getObjectInBackgroundWithId not working

I'm a beginner working with Parse and Swift. I need to update the object referred to in my viewDidLoad in another function within the same controller. How do I pass the currently loaded object's objectId without having to hardcode it like this:
query.getObjectInBackgroundWithId("8DkYgraEJq")
Here is my viewDidLoad function:
override func viewDidLoad() {
var query = PFQuery(className: "CheckedBaggage")
query.orderByAscending("createdAt")
query.whereKey("respondedTo", notEqualTo: true)
query.getFirstObjectInBackgroundWithBlock {
(CheckedBaggage: PFObject!, error: NSError!) -> Void in
if error != nil {
println("The getFirstObject request failed.")
} else {
// The find succeeded.
self.randomBaggageLabel.text = CheckedBaggage.objectForKey("message") as? NSString
CheckedBaggage.save()
println(CheckedBaggage.objectId)
let baggageId = CheckedBaggage.objectId
println("Successfully retrieved the object.")
}
}
I would like to try and pass the variable baggageId, which should be the object's ID as a string, as an argument to the getObjectInBackgroundWithId block in my carryIt function:
#IBAction func carryIt(sender: AnyObject!) {
println("CarryIt is being called")
var query = PFQuery(className: "CheckedBaggage")
query.getObjectInBackgroundWithId(baggageId) {
(CheckedBaggage: PFObject?, error: NSError?) -> Void in
if error != nil {
println(error)
} else if let CheckedBaggage = CheckedBaggage {
println("object hello!")
CheckedBaggage["respondedTo"] = true
CheckedBaggage["response"] = self.kindnessMessage.text
CheckedBaggage.save()
}
}
}
But I'm getting an "unresolved identifier" error. It updates my Parse database perfectly fine if I hardcode the object ID, but I can't do it this way. Here's a screenshot of the error:
Thank you so much for your help!
You have to initialize baggageId. To use it in multiple functions, it must be scoped at class level as the comment said. To set it after it has been declared, it must be a "var", not a constant "let".
var baggageId = ""
func viewDidload() {
var query = ...
query.get... {
baggageId = CheckedBaggege.objectId
}
}
func shipIt() {
var query = ...
query.getObjectWithId(baggageId) ...
}

Swift - Parse - Check if username is taken

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

Letting User Update Password - Parse - Swift

I am trying the code below to let users update their password when a uibutton is clicked. However, ever when I enter the current password right, I get the "wrong current password" message. I guess the system does not compare the entered value with the current password right. Without the first if condition, I can update the password. But I want the user to enter current password for security reasons first. May anyone help?
#IBAction func updatePasswordBtn(sender: AnyObject) {
var passwordCheckQuery = PFQuery(className: "_User")
passwordCheckQuery.whereKey("username", equalTo: PFUser.currentUser()!.username!)
var objects = passwordCheckQuery.findObjects()
for object in objects! {
if currentPassword.text == PFUser.currentUser()!.password {
if newPassword.text == retypeNewPassword.text {
var query6 = PFUser.query()
query6!.whereKey("username", equalTo: PFUser.currentUser()!.username!)
query6!.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
for object6 in objects! {
var ob6:PFObject = object6 as! PFObject
ob6["password"] = self.newPassword.text
ob6.save()
}
}
}
else { println("passwords dont match")
}
}
else { println("wrong current password")
}
}
}
I updated my code as below after #Wains comment and it started to work.
#IBAction func updatePasswordBtn(sender: AnyObject) {
PFUser.logInWithUsernameInBackground(PFUser.currentUser()!.username!, password: currentPassword.text) {
(user:PFUser?, error:NSError?) -> Void in
if error == nil {
var passwordCheckQuery = PFQuery(className: "_User")
passwordCheckQuery.whereKey("username", equalTo: PFUser.currentUser()!.username!)
var objects = passwordCheckQuery.findObjects()
for object in objects! {
if self.newPassword.text == self.retypeNewPassword.text {
var query6 = PFUser.query()
query6!.whereKey("username", equalTo: PFUser.currentUser()!.username!)
query6!.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
for object6 in objects! {
var ob6:PFObject = object6 as! PFObject
ob6["password"] = self.newPassword.text
ob6.save()
println("successfully updated password")
}
}
}
else { println("passwords dont match")
}
}
} else {
println("wrong current password")
}
}
}
The password isn't available to you, so doing PFUser.currentUser()!.password isn't going to give you something you can check against. To verify a password you need to log the user in - i.e. take the user name and password they give you and use PFUser.logInWithUsernameInBackground.... If you get a valid user back then you can set the password and save.

Retrieve values out of PFObject

I have a save button to save Score and Playername to GameScore in Parse. When I load the GameScore from Parse I want to set the value that i loaded to the variable "score". This don't work, can anyone please tell me what i am doing wrong?
Thanks
Exapmle: let score = gameScore["score"] as Int
// Load button tapped
#IBAction func loadButtonTapped(sender: UIButton) {
var query = PFQuery(className:"GameScore")
query.getObjectInBackgroundWithId("F1efANYzOE") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
println(gameScore)
let score = gameScore["score"] as Int
} else {
println(error)
}
}
}
}
Try this following code for retrieving specific data from specific columns. You have to enter your object name, Object ID and column name in the below code and run it. It will work.
let query = PFQuery(className:"Your Object name")
query.getObjectInBackgroundWithId("Your Object ID") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil {
print(gameScore!.objectForKey("your column name") as! String)
} else {
print(error)
}
}

Resources