Create a PFObject and PFRelation after PFUser Sign Up

177 views Asked by At

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";
    }
});
2

There are 2 answers

0
Himanshu gupta On BEST ANSWER

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
    }
});
0
Icaro On

How to create a relationship in Parse.com

//first you create the user that will relate with something
var user = PFUser.currentUser()
//Then you create a relationship type eg. friend, likes, score (in this case like similar to facebook or twitter
var relation = user.relationForKey("likes")
//after you add the PFObject that it relates to eg. a friend, a post, a twitte (see how to acquire this PFObejct below)
relation.addObject(post)
//Now you just need to save the relation
user.saveInBackgroundWithBlock {
  (success: Bool, error: NSError?) -> Void in
  if (success) {
    // The post has been added to the user's likes relation.
  } else {
    // There was a problem, check error.description
  }
}

If you need to acquire a PFObject to add to the relation this is how you do:

var post = myComment["parent"] as PFObject
post.fetchIfNeededInBackgroundWithBlock {
  (post: PFObject?, error: NSError?) -> Void in
  let title = post?["title"] as? NSString
  // do something with your title variable
}

I hope that helps you!