I want to set user name to a label because my block ("findObjectsInBackgroundWithBlock") is taking time to complete and label.text sets nil .
how to set label text after completing the block??
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 am getting 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
}
}
}
}
}
UIKit.UILabel class is used to create a label in iOS swift source code programmatically. You can change label text, label text color, label background color, label border width, label border color by setting it’s properties.
You can also change the label text wrap method by setting the label object’s lineBreakMode property. This example will tell you how to create a swift label object programmatically in source code, how to align the label text, and how to change the label text line numbers and wrap the label text words.
// Set numberOfLines to 0 means the label text can has any number lines. // Initialize the tips message label. // Set message label's initial text alignment to center. // Add the two labels to the screen. /* This function will be invoked when click button 'Change Label Text Alignment'. */ labelOne.text = "Hello swift label."
// Initialize the tips message label. // Set message label's initial text alignment to center. // Add the two labels to the screen. /* This function will be invoked when click button 'Change Label Text Alignment'. */ labelOne.text = "Hello swift label."
You can use a property observer here like this:
var userName: String? {
didset {
if let name = username {
lblUserName.text = name
}
}
}
You can add a completion handler function argument to your getCurrentUser function and call that handler when you retrived the 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 complition function like this:
getCurrentUser() { (result: String) in
self.lblUserName.text = result
}
I cannot prove it is fully working code as I don't have XCode now to test it. But you should get the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With