I am having trouble getting data to load correctly in my ViewDidAppear method when using a Firebase login. I want the user to press the login button, the app to retrieve the user's information from Firebase, and then display it in the next view controller (which is part of a new tab bar controller).
When I use breakpoints, I can see that the new view appears and THEN the data is pulled from Firebase. I need the data to be loaded from Firebase before the view appears.
Here is my code for the login button:
let userSettings = NSUserDefaults.standardUserDefaults()
@IBAction func signInButton(sender: AnyObject) {
ref.authUser(emailTextField.text, password: passwordTextField.text) { (error, authData) -> Void in
if error != nil {
let accountError = UIAlertController(title: "Error logging in", message: "Please try again", preferredStyle: .Alert)
accountError.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(accountError, animated: true, completion: nil)
} else {
userID = ref.authData!.uid
userSettings.setObject(userID!, forKey: "firebaseUserID")
let playNumberRef = Firebase(url:"https://(removed for security).firebaseIO.com/users/\(userID!)/playNumber")
//Check Firebase for the user's last playnumber and set it in the user defaults
playNumberRef.observeSingleEventOfType(.Value, withBlock: { snap in
//Convert type AnyObject to NSNumber so that we can check its value
if let checkPlay = snap.value as? NSNumber {
userSettings.setInteger(Int(checkPlay), forKey: "playNumber")
}})
Here is my code in the viewWillAppear method:
var playNumber = userSettings.integerForKey("playNumber")
dayCounterLabel.text = "Day \(playNumber)"
When the view first appears, the dayCounterLabel.text has not been updated. If I navigate to a different tab and then navigate back, it updates.
How can get the data to save into the user defaults prior to the view appearing?