Daniel Patriarca
Daniel Patriarca

Reputation: 365

When posting to parse server does the newly created object Id get returned

I am using parse server as the back end for an iOS app. A button tap "creates a post" that can have as many images uploaded with the post as the user queues up.

The issue is that I don't know the number of images that the user will upload so I would need to have 2 classes in the parse database: "Posts" for the post information, and "Images" for each image uploaded. How do I get the autogenerated id for the post so that I can associate the images to the post?

Is there a way in parse to return the new id that was generated after a successful insert? If not, is the only solution to insert and then run an immediate select for most recent post by that user? If the app is on more than one device that could lead to errors so I thought there may be a better approach.

Upvotes: 0

Views: 50

Answers (2)

Daniel Patriarca
Daniel Patriarca

Reputation: 365

I found this answer on the Parse documentation, including it in case it helps others... Relational Data Objects can have relationships with other objects. To model this behavior, any PFObject can be used as a value in other PFObjects. Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency.

For example, each Comment in a blogging app might correspond to one Post. To create a new Post with a single Comment, you could write:

// Create the post
var myPost = PFObject(className:"Post")
myPost["title"] = "I'm Hungry"
myPost["content"] = "Where should we go for lunch?"

// Create the comment
var myComment = PFObject(className:"Comment")
myComment["content"] = "Let's do Sushirrito."

// Add a relation between the Post and Comment
myComment["parent"] = myPost

// This will save both myPost and myComment
myComment.saveInBackground()

Upvotes: 0

kathayatnk
kathayatnk

Reputation: 1015

I believe when a PFObject is saved and the success block is executed, you should be able to see the snapshot of the objectId there. As an example

//This is my parse class
let object = MYPFObject()
    object.data = "Hello"


 ///now when the object is saved
object.saveInBackground { (success, error) in

       //Here printing the object itself will give you the object ID
        debugPrint(object)
}

Sample output would be something like

<MYPFObject: 0x1c02b2660, objectId: jE01A8upDM, localId: (null)> {
     ACL = "<PFACL: 0x1c403f3e0>";
     data = Hello;
}

Upvotes: 2

Related Questions