Setting label text after completion of a Swift block

I want to set the username for the label because my block ("findObjectsInBackgroundWithBlock") takes time and label.text sets nil .

How to set label text after block completion?

class test { var userName: String? // variable to access user name returned by block private func loadData() { getCurrentUser() lblUserName.text = userName } } 

This is the block where I get user data from Parse.

 private func getCurrentUser() { if PFUser.currentUser() != nil { currentUser = PFUser.currentUser()?.username let query = PFQuery(className: "_User") query.whereKey("username", equalTo: currentUser!) query.findObjectsInBackgroundWithBlock { (currentUsers, error) -> Void in if error == nil { for user in currentUsers! { userName = user["name"] as? String } } } } } 
+6
source share
4 answers

You can use the property observer here as follows:

 var userName: String? { didset { if let name = username { lblUserName.text = name } } } 
+1
source

You can add an argument to the completion handler function in your getCurrentUser function and call the handler when retrieving data:

 private func getCurrentUser(completion: (result: String) -> Void) { if PFUser.currentUser() != nil { currentUser = PFUser.currentUser()?.username let query = PFQuery(className: "_User") query.whereKey("username", equalTo: currentUser!) query.findObjectsInBackgroundWithBlock { (currentUsers, error) -> Void in if error == nil { for user in currentUsers! { completion(user["name"] as? String) } } } } } 

Then pass the addition function as follows:

 getCurrentUser() { (result: String) in self.lblUserName.text = result } 

I can not prove that this is fully working code, since I do not have Xcode to test it. But you should get this idea.

+1
source

You can use the callback that you define in the getCurrentUser function

 private func loadData() { getCurrentUser({ self.lblUserName.text = userName }) } private func getCurrentUser(callback: () -> ()){ // Your code callback() } 

Swift closures

0
source

query.findObjectsInBackgroundWithBlock is an asynchronous call. The completion block provided to it is launched in a separate thread after receiving a response from the server.

If you put a breakpoint on the line getCurrentUser() and enter the stream, you can clearly understand the stream.

There are different ways to achieve a result,

  • You can set the property observer for userName and set the change to your lblUserName
 var userName: String? { willSet(newUserName) { if let username = newUserName { lblUserName.text = username } } } 
  1. You can update the lblUserName value as part of your completion block
0
source

All Articles