Tarvo Mäesepp Tarvo Mäesepp - 13 days ago 5
Swift Question

Updating label if value in singleton changes

I am getting some user information from Firebase and storing it into singleton. After that every time the value changes I want that the label changes also but it doesn't until I terminate the app and come back in.

How should I update label if value changes in singleton?

I have tab views. In first tab I assign values and in second tab I try to put the values to label.

This is my singleton:

class CurrentUser: NSObject
{
var generalDetails: User = User()/// Consecutive declarations on a line must be separated by ';'

static let sharedInstance = CurrentUser()


fileprivate override init(){
super.init()
}

}


And like this I assign values:

self.databaseRef.child("users").child(user.uid).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in

guard let firebaseValue = snapshot.value as? [String:AnyObject], let userName = firebaseValue["username"] as? String, let email = firebaseValue["email"] as? String, let reputation = firebaseValue["reputation"] as? Int, let profilePicURL = firebaseValue["profileImageUrl"] as? String
else
{
print("Error with FrB snapshot")//Here
return
}

//Set values
self.currentUser.generalDetails = User(userName: userName, email: email, reputation: reputation, profileImageURL: profilePicURL, uid: user.uid)
}


And if I want to put the value to the label I simply do this(This reputation is the only thing that can change often):

self.reputationLabel.text = String(self.currentUser.generalDetails.reputation)

Answer

You can do either of these:-

  • Communicate between the singleton and your class with delegate-protocol method , fire the delegate method in the class whenever your repo changes and update your label.

  • Open a different thread in your network link for the user's reputation in the viewController itself:-

    override func viewDidLoad() {
    super.viewDidLoad()
    
    FIRDatabase.database().reference().child("users/\(FIRAuth.auth()!.currentUser!.uid)\reputation").observe(.childChanged, with: {(Snapshot) in
    
        print(Snapshot.value!)
        //Update yor label
    })
    

    which will get called every time the value of reputation changes.