致命错误Firebase快照

时间:2017-09-15 04:36:00

标签: swift xcode firebase firebase-realtime-database

每次我运行时都会收到此错误:致命错误:

  

在打开2017-09-15的可选值时,意外地发现了nil   06:30:04.650075 + 0200 RollerBank [845:211470]致命错误:意外   在解包一个Optional值时发现nil。

我不知道我做错了什么。有谁可以帮助我吗?

func reload(){
            //get data
            Database.database().reference().child("Rollerbanken").observe(.value, with: { (snapshot) in



                for item in snapshot.children{

                    if let itemDict = snapshot.value as? NSDictionary {


                        let annotation = MKPointAnnotation()


                        annotation.title = itemDict["TypeControle"] as! String
                        let tijd = itemDict["Tijd"] as! String
                        annotation.subtitle = "Geplaatst om \(tijd)"


                        let getLatitude = itemDict["Latitude"] as! Double
                        let getLongitude = itemDict["Longitude"] as! Double

                        annotation.coordinate = CLLocationCoordinate2D(latitude: getLatitude, longitude: getLongitude)

                        self.map.addAnnotation(annotation)

                    }
                }
            })
        }

Structure

3 个答案:

答案 0 :(得分:0)

我相信你的问题在于这一行

if let itemDict = snapshot.value as? NSDictionary

你正在使你的itemDict成为整个对象的字典。因此,您没有“TypeControle”键,您拥有生成的Firebase ID的密钥。您可以获取child.value来获取您正在寻找的字典我相信。

if let itemDict = item.value as? NSDictionary

答案 1 :(得分:0)

使用此方法解析从Firebase收到的值。

if let value = snapshot.value as? Dictionary<String, Any> {

    for key in value.keys {
            if let itemDict = value[key] as? Dictionary<String, AnyObject> {

                let annotation = MKPointAnnotation()
                annotation.title = itemDict["TypeControle"] as! String
                let tijd = itemDict["Tijd"] as! String
                annotation.subtitle = "Geplaatst om \(tijd)"

                let getLatitude = itemDict["Latitude"] as? String
                let getLongitude = itemDict["Longitude"] as? String
                if let lat = getLatitude, let long = getLongitude {
                    annotation.coordinate = CLLocationCoordinate2D(latitude: Double(lat), longitude: Double(long))

                  self.map.addAnnotation(annotation) 
            }
       }
    }
 }

答案 2 :(得分:0)

将您的代码更改为:

for item in snapshot.children {

    let snapshotValue = item.value as! [String: AnyObject]
    key  = snapshotValue["TypeControle"] as! String
    tijd = snapshotValue["tijd "] as! String
    // etc..
}

希望有所帮助