从Firebase Data Pull

时间:2017-01-11 06:52:02

标签: ios swift firebase firebase-realtime-database

我尝试创建一个带有可用初始化程序的类,该初始化程序采用FIRUser和FIRDatabaseReference。它从Firebase数据库下载数据,并根据返回的内容设置自己的变量。否则,初始化器应该会失败。

发生的事情是数据是在闭包中下载的,但是一切都恢复到默认值,好像下载从未发生过一样!

我真的想在类初始化程序中包含此服务器聊天逻辑。我可以安全地实现这一目标吗?到目前为止,我已经尝试了很多东西,无法弄清楚。

    init?(from user: FIRUser, withUserReference ref: FIRDatabaseReference){
    let userID = user.uid

    var init_succeeded = false

    //These values don't matter. If the init fails
    //It'll return an empty class.
    //Yes this is a hack lol

    self.incognito = false
    self.email = "NO"
    self.username = "NOPE"
    self.ref = ref
    self.fir_user = user
    self.mute_all = false

    //Getting the information from the database
    ref.child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        //Unpacking user preferences
        self.incognito = (value?["incognito"] as? Bool)!
        self.mute_all = (value?["mute_all"] as? Bool)!
        self.email = (value?["email"] as? String)!
        self.username = (value?["username"] as? String)!
        init_succeeded = true
    }) { (error) in
        print("ERROR : \(error.localizedDescription)")
    }

    if !init_succeeded { return nil }
}

谢谢! - 基南

1 个答案:

答案 0 :(得分:0)

简单回答:

当函数依赖于异步语句时,您根本不应该return来自函数的值。 此方法将始终返回nil,因为在方法返回后,init_succeeded很可能设置为true 。请记住,Firebase查询是异步的,因此一旦调用observeSingleEvent,该函数就不会等待该语句完成执行,它只是异步运行它并继续执行其余代码(即{{} 1}}在这种情况下)。

完成闭包是你可以得到的最接近的(但是你的代码不会完全包含在初始化程序中):

return

现在基本上就像这样使用它

init(from user: FIRUser, withUserReference ref: FIRDatabaseReference, completion: @escaping (Bool) -> Void){
let userID = user.uid

// default values
self.incognito = false
self.email = "NO"
self.username = "NOPE"
self.ref = ref
self.fir_user = user
self.mute_all = false

//Getting the information from the database
ref.child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
    // Get user value
    let value = snapshot.value as? NSDictionary
    //Unpacking user preferences
    self.incognito = (value?["incognito"] as? Bool)!
    self.mute_all = (value?["mute_all"] as? Bool)!
    self.email = (value?["email"] as? String)!
    self.username = (value?["username"] as? String)!

    completion(true)     // true = success
}) { (error) in
    completion(false)    // false = failed
    print("ERROR : \(error.localizedDescription)")
}

}

我建议不要一般在初始化程序中检索数据。也许编写另一个专门用于检索数据的函数,并仅在let myObject = myClass(from: someUser, withUserReference: someRef, completion: { success in if success { // initialization succeeded } else { // initialization failed } })

中设置默认值