【问题标题】:iOS Firebase retrieve data from child nodes always niliOS Firebase 从子节点检索数据始终为零
【发布时间】:2019-03-16 16:38:46
【问题描述】:

我正在尝试读取存储在随机子 ID 下的纬度和经度数据。我的数据结构如下:

这是我的检索代码。

ref.child("locations").observe(.value, with: { snapshot in
for child in snapshot.children  {
                let valueD = child as! DataSnapshot
                let randomkey = valueD.key
                print(randomkey)
                print(valueD.value)
                let lat = (valueD.value as? NSDictionary)?["Latitude"] as? String
                print(lat) 
}})

对于valueD.value,控制台会打印这个(这是正确的)

Optional({
Latitude = "1.342433333333333";
Longitude = "103.9639883333333";
Type = 0;
})

但是,对于lat,它返回nil

为什么lat 没有价值?我该如何解决这个问题?谢谢!

【问题讨论】:

  • 首先,尝试打印这个(valueD.value as?NSDictionary)。检查你是否得到字典输出。

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

感谢大家的回复!这确实是关于打开 Optional 的问题。

我尝试了以前的解决方案。这个解决方案最适合我,因为我从我的数据库中知道我肯定会有纬度和经度数据:换成感叹号。

let latitude = (valueD.value as! NSDictionary)["Latitude"] as! Double

【讨论】:

  • 啊太棒了!看起来它是您代码中的字符串,但实际上可能是您的屏幕截图中的 Double !很高兴你发现了!
【解决方案2】:

您必须安全地打开可选的包装。有很多方法可以做到这一点。我最喜欢的方法之一是使用guard let 声明

// This output already says 'Optional'
Optional({
Latitude = "1.342433333333333";
Longitude = "103.9639883333333";
Type = 0;
})

像这样打开它:

ref.child("locations").observe(.value, with: { snapshot in
for child in snapshot.children  {

                let valueD = child as! DataSnapshot
                let randomkey = valueD.key
                print(randomkey)
                print(valueD.value)

                // Unwrap
                guard let childValue = valueD.value else { return }
                print(childValue["Latitude"])
}})

【讨论】:

    【解决方案3】:

    你试过if let lat = child.value["Latitude"] as? Double 吗?比如:

    ref.child("locations").observe(.value, with: { snapshot in
    for child in snapshot.children  {
    
                    let valueD = child as! DataSnapshot
                    let randomkey = valueD.key
                    print(randomkey)
                    print(valueD.value)
    
                    if let lat = child.value["Latitude"] as? Double {
                        print(lat)
                    }
    }})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多