【问题标题】:How to make a CompletionHandler with Firebase Swift 3如何使用 Firebase Swift 3 制作 CompletionHandler
【发布时间】:2017-11-17 19:29:59
【问题描述】:

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

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)。

这是我的 Firebase 数据库:

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

【问题讨论】:

  • 向我们展示子“Player_1”的数据库结构。错误不在完成处理程序中,而是在类型中。类似于 db 的屏幕截图
  • firDataSnapshot.value 实际上是一个字符串吗?你能调试一下那个值吗?
  • @petul 是的,它是一个字符串!
  • @Max0u 通常它会返回一个字典。您可以尝试让 value = firDataSnapshot.value as 吗? NS词典。然后你可以像往常一样在字典中访问你的值
  • 请告诉我们调用你的hardProcessingWithString函数的代码...

标签: xcode firebase swift3 firebase-realtime-database completionhandler


【解决方案1】:

第 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
}

【讨论】:

  • 阅读他的“无法将类型 '__NSDictionaryM' (0x102e292b0) 的值转换为 'NSString' (0x102434c60)。”。问题不在于完成处理程序的组织。
  • @Alwin 但是我怎样才能返回函数中的值?我想获取 firDataSnapshot 的值
  • 创建一个全局变量并设置getter和setter
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
相关资源
最近更新 更多