如何使用Firebase Swift制作CompletionHandler 3
问题描述:
我需要从Firebase获取一些信息才能在UIViewCell
上找到它。但问题是,在他获得所有价值之前,函数会返回。我知道那是因为它是异步的,我试图做一个完成处理这样的:如何使用Firebase Swift制作CompletionHandler 3
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
}
当我打电话的功能我得到这个错误:
无法将'__NSDictionaryM'(0x102e292b0)类型的值转换为'NSString'(0x102434c60)。
这里是我的火力地堡数据库:
或者,如果你知道如何使火力地堡许诺让我知道!
答
第1步:
创建一个像Constant.swift这样的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
}
告诉我们孩子的数据库结构法 “PLAYER_1”。错误不在完成处理程序中,但在类型中。像db –
的屏幕截图是firDataSnapshot.value实际上是一个字符串?你能调试这个值吗? – petul
@petul是的,它是一个字符串! – Max0u