How to synchronously retrieve PFUser objectForKey in Swift

269 Views Asked by At

I am trying to synchronously retrieve a PFUser object information. However, I've tried using fetch, but I keep on getting implementation errors. I would like to find for example: PFUser.currentUser()?.objectForKey("scoreNumber"), but I am not getting the updated value. I was told I would find it using fetch, but I am unable to implement objectForKey in my fetch function.

Some of the attempts

var score: String!
func retrieveScore(){
    guard let myUser = PFUser.currentUser() else { return }
      do{ let data = try myUser.objectForKey("scoreNumber")?.fetch()
        try scoreNumber = data! as! String
    }catch{}
}

Another one

let userScore = PFUser.currentUser()?.objectForKey("scoreNumber")
let userScore2 = userScore.fetch()
1

There are 1 best solutions below

0
Jake T. On

You shouldn't save the user for NSUserDefaults. Parse SDK does a good job of managing your sessions for you. Just have a specific log out button that calls the [PFUser logout]` function.

So, fetch is an asynchronous operation. This means that it runs on a separate thread, and then the main thread will continue executing the next commands. So, you're calling fetch, which fetches an object in the background, but then you are trying to access a value from the object that hasn't been fetched yet. You need to access the object from within the block handling the results of the fetch call.

When you call fetch the way you did, just with .fetch(), it runs in the background but doesn't alert you when you have the data, nor if the fetch failed. This is not a good way to get data you're going to need immediately.

You need to use fetchInBackgroundWithBlock()

scoreNumber.fetchInBackgroundWithBlock() {
  (scoreNumber: PFObject?, error: NSError?) -> Void in
  if error == nil && scoreNumber != nil {
    print(scoreNumber)
  } else {
    print(error)
  }
}