如何使用 Firebase 制作 CompletionHandler Swift 3

How to make a CompletionHandler with Firebase Swift 3

我需要从 Firebase 获取一些信息才能在 UIViewCell 上发布它。但是问题是函数return之前他得到了所有的值。我知道那是因为它是异步的,我试图制作一个这样的完成处理程序:

static func hardProcessingWithString(input: String, completion: @escaping (_ result: String) -> Void) {
    Database.database().reference().child("Player_1").observe(.value) {
        (firDataSnapshot) in
        completion((firDataSnapshot.value as? String)!)    
    }
}

这就是我尝试获取值的方式:

var myVar: String!
hardProcessingWithString(input: "commands"){
        (result: String) in
        myVar = result
}

调用函数时出现此错误:

Could not cast value of type '__NSDictionaryM' (0x102e292b0) to 'NSString' (0x102434c60).

这是我的 Firebase 数据库:

或者,如果您知道如何使用 Firebase 做出承诺,请告诉我!

第 1 步:

创建一个 swift 文件,如 Constant.swift。然后将下面的代码放入其中

typealias DownloadComplete = () -> ()

第 2 步:

在你想要的地方创建一个函数。

func hardProcessingWithString(completed: @escaping DownloadComplete) {
Database.database().reference().child("Player_1").observe (.value, with: { (firDataSnapshot) in

// put your code here

completed()
})
}

第 3 步:

当您在代码中调用上述方法时

 hardProcessingWithString() {
    // you can get the result here
}