Search code examples
iosswiftparse-platformpfuser

How to change PFUser password in Swift?


I've tried updating the same way you would update a PFUser's email and even tried converting obj-c code (from other questions); neither worked. I also have no idea how to use Cloud Code (well...I installed it but I don't know how to pass information into Cloud Code or how to use JavaScript). Is there a way to update a users password without having to send the reset email?


Solution

  • You can not change a user's password that way for security reasons. You have two choices

    • Password Reset Email

    • Cloud Code Function to Reset the Password

    As I understand that you do not know JavaScript, here is a cloud code function that you can use to reset the user's password, as well as a way to call the function using Swift.

    Function (in JavaScript):

    Parse.Cloud.define("changeUserPassword", function(request, response) {
      // Set up to modify user data
      Parse.Cloud.useMasterKey();
    var query = new Parse.Query(Parse.User);
    query.equalTo("username", request.params.username);  // find all the women
    query.first({
      success: function(myUser) {
        // Successfully retrieved the object.
    myUser.set("password", request.params.newPassword);
    
    myUser.save(null, {
            success: function(myUser) {
              // The user was saved successfully.
              response.success("Successfully updated user.");
            },
            error: function(myUser, error) {
              // The save failed.
              // error is a Parse.Error with an error code and description.
              response.error("Could not save changes to user.");
            }
          });
    
      },
      error: function(error) {
        alert("Error: " + error.code + " " + error.message);
      }
    });
    });
    

    Swift code to call the above function:

    PFCloud.callFunctionInBackground("changeUserPassword", withParameters: ["username" : "MyCoolUsername", "newPassword" : passwordField.text]) {
      (result: AnyObject?, error: NSError?) -> Void in
      if (error == nil) {
        // result is "Successfully updated user."
      }
    }
    

    Good luck!