How do I load data from an async callback into the parent class attributes?
I have a database in Firebase which holds my user profiles. I want to be able to pass in the node key and have it populate the object with the given values.
Because it works async, I am getting the default values from the object because the callback completes after the class init.
Obviously I'm new to Swift so apologies if the terminology is sketchy.
I read this thread which talked about inversion of control pattern, and whilst it made sense, I couldn't work out how to actually initiate the class.
UserProfile.swift:
import UIKit
import Firebase
import FBSDKCoreKit
class UserProfile{
var ref: DatabaseReference!
var uid : String = ""
var name : String = ""
var location : String = ""
//var posts = [String]()
init(uid : String) {
self.ref = Database.database().reference().child("user_profiles").child(uid)
self.ref.observeSingleEvent(of: .value, with: { (snapshot) in
let userObj = snapshot.value as? [String : AnyObject] ?? [:]
self.uid = uid
self.name = userObj["name"] as! String
self.location = userObj["location"] as! String
})
}
}
ViewController.swift
let user = UserProfile(uid : "NODEKEYINFIREBASE")
print(user)
Output:
()