Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get objectId immediately after save data with Parse and swift

    var cardObject = PFObject(className: "YourCard")
    cardObject["cardNumber"] = cardNumber
    cardObject["balance"] = balance
    cardObject["expire"] = date
    cardObject["validFlg"] = cardStatus
    cardObject.saveInBackgroundWithBlock {
        (success: Bool!, error: NSError!) -> Void in
        if (success != nil) {
            NSLog("Object created with id: \(cardObject.objectId)")
        } else {
            NSLog("%@", error)
        }
    }
    dbId = cardObject.objectId

I couldn't get objectId, how can I get it? Thank you very much in advance.

like image 937
user4473065 Avatar asked Mar 18 '23 06:03

user4473065


1 Answers

As the name of your function already says, it is a function which is called asynchron. That means that the main thread doesn't wait for the function to finish. So you will get an (still) empty objectId.

To get your objectID after saveInBackground is finished, you have to put your line where you get the ID into the if-clause.

 var cardObject = PFObject(className: "YourCard")
    cardObject["cardNumber"] = cardNumber
    cardObject["balance"] = balance
    cardObject["expire"] = date
    cardObject["validFlg"] = cardStatus
    cardObject.saveInBackgroundWithBlock {
        (success: Bool!, error: NSError!) -> Void in
        if (success != nil) {
            NSLog("Object created with id: \(cardObject.objectId)")
            //Gets called if save was done properly
            dbId = cardObject.objectId

        } else {
            NSLog("%@", error)
        }
    }

Another option would be to call save() in the main thread. That way the function finishes before you call the objectId. Parse doesn't recommend that, but it's a possibility:

cardObject.save()
dbId = cardObject.objectId
like image 125
Christian Avatar answered Apr 30 '23 05:04

Christian