【问题标题】:Firebase and Completion handlerFirebase 和完成处理程序
【发布时间】:2016-09-04 05:11:11
【问题描述】:

我目前正在使用 firebase 来检索用户信息。一旦我收到数据,我想在所有闭包之外使用数据,我创建了一个完成块,问题是我无法将完成变量添加到结果中,因为结果在另一个闭包内。如何解决这个问题。提前感谢您的帮助。

 func userInfo(userId:String,completion:(result:String)->Void){


        fireBaseAPI().childRef("version_one/frontEnd/users/\(fireBaseAPI().currentUserId()!)/email").observeEventType(.Value, withBlock: {snapshot in

            let email = snapshot.value as! String

            //this is incorrect because it is inside a firebase closure how can I make it work I know i have it outside the closure but i will not be able to retrieve the info from firebase
            result = email

        })




    }

【问题讨论】:

  • 更清楚你想要什么,并提供更多关于fireBaseAPI()的信息

标签: swift firebase


【解决方案1】:

据我所知你的问题::---

您想在 completionBlock: 中发送用户的电子邮件 ID,但我仍然不知道 fireBaseAPI() 是什么:-

func userInfo(userId:String,completion:((result:String)->Void){
fireBaseAPI().childRef("version_one/frontEnd/users/\(fireBaseAPI().currentUserId()!)/email").observeEventType(.Value, withBlock: {snapshot in

        let email = snapshot.value as! String
        completion(result:email)
    })
}

【讨论】:

    【解决方案2】:

    您可以在您的类中(在闭包之外)创建一个变量,然后将 snapshot.value 结果存储在该变量中,如下所示:

    编辑

    var emailResult: String?
    
    func getUserEmail {
        fireBaseAPI().child("version_one/frontEnd/users/\(fireBaseAPI().currentUserId()!)/email").observeEventType(.Value, withBlock: {snapshot in
            let email = snapshot.value as! String
            self.emailResult = email
        })
    }
    

    【讨论】:

    • 该结果将始终返回 nil,因为变量已设置它位于闭包内,这就是我必须制作完成处理程序的原因
    • 我刚刚编辑了我的答案。我不知道你班上其他人的样子,但你能像我上面写的那样做吗?为什么你需要在你原来的userInfo 方法中传入userId:String,因为你调用fireBaseAPI().currentUserId() 来获取用户ID?为什么需要在 Firebase 闭包 withBlock 之上添加完成处理程序?
    • 嘿 iOSMoonSand。这确实将确保电子邮件结果在getUserEmail() 之外可用。 Firebase 异步加载数据,因此可以稍后(很多)调用回调。甚至“更糟”:Firebase 会继续同步数据,因此电子邮件结果可能会随着时间而改变。您的代码的主要问题是知道何时 电子邮件结果可用以及(甚至更难)何时更新。这就是为什么 Dravidian 的回调方法(虽然最初不太直观)更适合这些调用。
    猜你喜欢
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多