iosswiftparse-platformpfuserpfrelation

Create a PFObject and PFRelation after PFUser Sign Up


In my structure, I would like to signUp a User and assign a Group to it directly (Many to many relationship model)

Below is how I signUp the user. after completion, I have no idea how to relate to the PFObject using PFRelation.

Any thoughts please?

// SIGN UP USER
var user = PFUser();
user.email = emailTextField.text;
user.username = emailTextField.text;
user.password = passwordTextField.text;

user.signUpInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in
    if error == nil {
        //Create a PFObject
        var group = CustomPFObject();
        group.name = "My First Group";
    }
});

Solution

  • You can do something like this:

    user.signUpInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in
        if error == nil {
    
            //Create a PFObject
    
            var group = CustomPFObject();
            group.name = "My First Group";
    
            var relation: PFRelation = group.relationForKey("your_key")
    
            relation.addObject(user)
    
            group.save() // synchronous
    
            group.saveInBackgroundWithBlock { (Bool, NSError?) -> Void in
    
            }   // async
        }
    });