我正在User通过 Firebase DataSnapshot 实例化一个类。在调用初始化程序时,它应该通过and方法的 @escaping 完成处理程序(使用 Firebase 的方法)init(snapshot: DataSnapshot)从两个不同的数据库引用中异步检索值,即pictureRefand 。为了避免在所有成员初始化错误之前闭包捕获的“自我”,我必须使用and的临时值初始化and 。但是,当通过 实例化类时,这些值实际上从未使用检索到的 Firebase 值进行更新。nameRefgetFirebasePictureURLgetFirebaseNameStringobserveSingleEventfullNamepictureURL""URL(string: "initial")User(snapshot: DataSnapshot)
import Firebase
class User {
var uid: String
var fullName: String? = ""
var pictureURL: URL? = URL(string: "initial")
//DataSnapshot Initializer
init(snapshot: DataSnapshot) {
self.uid = snapshot.key
getFirebasePictureURL(userId: uid) { (url) in
self.getFirebaseNameString(userId: self.uid) { (fullName) in
self.fullName = fullName
self.profilePictureURL = url
}
}
func getFirebasePictureURL(userId: String, completion: @escaping (_ url: URL) -> Void) {
let currentUserId = userId
//Firebase database picture reference
let pictureRef = Database.database().reference(withPath: "pictureChildPath")
pictureRef.observeSingleEvent(of: .value, with: { snapshot in
//Picture url string
let pictureString = snapshot.value as! String
//Completion handler (escaping)
completion(URL(string: pictureString)!)
})
}
func getFirebaseNameString(userId: String, completion: @escaping (_ fullName: String) -> Void) {
let currentUserId = userId
//Firebase database name reference
let nameRef = Database.database().reference(withPath: "nameChildPath")
nameRef.observeSingleEvent(of: .value, with: { snapshot in
let fullName = snapshot.value as? String
//Completion handler (escaping)
completion(fullName!)
})
}
}
发生这种情况是否有原因,我将如何解决这个问题,以便它初始化为检索到的值,而不是仅仅保留临时值?是不是因为
init不是异步的?
编辑:我正在从 Firebase 数据库的一个节点读取数据,并使用该数据创建一个新的节点子节点。初始化 User 类的方法将在数据库中创建这个新节点:
如您所见,子项使用临时值更新,因此程序执行似乎不等待回调。
任何帮助将非常感激!