首页 > 解决方案 > Type conversion error when reading data from Firebase

问题描述

I'am using mapkit to make a app, while I trying to get the user location from firebase it cause the error in these three line

let dict = recipeSnap.value as! [String:Double?]

let latitude = dict["latitude"] as? Double?

let longitude = dict["longitude"] as? Double?.

I have tried to replace the double by string but new error happen, then I tried replace it by AnyObject, it works, but the data is like Optional(37.785834). and it always cause the error while I use AnyObject data to do other things.

here is my code

@objc func updateTimer(){

    print("Update location")
    let location = locman.location!.coordinate
    lat = String(location.latitude)
    long = String(location.longitude)
    print(lat)
    print(long)
    let ref = Database.database().reference()
    ref.child("location/User1/longitude").setValue(long)
    ref.child("location/User1/latitude").setValue(lat)
    ref.child("location").observeSingleEvent(of: .value) { (snapshot) in
          self.usern = snapshot.childrenCount
          for snap in snapshot.children{
              let aSnap = snap as! DataSnapshot  
              let dict = aSnap.value as! [String:Double?]
              let latitude = dict["latitude"] as? Double?
              let longitude = dict["longitude"] as? Double?
              print(dict)
              print(latitude)
              print(longitude)

              let point = MKPointAnnotation()
              point.title = "user"
            //point.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
              self.mapView.addAnnotation(point)
        }
    }
}

and here is my error

Could not cast value of type 'Swift._NSContiguousString' (0x1032681f8) to 'NSNumber' (0x1b7a1abf0). 2019-10-10 20:24:05. mapkitMap[1468:709956] Could not cast value of type 'Swift._NSContiguousString' (0x1032681f8) to 'NSNumber' (0x1b7a1abf0). Optional(37.785834)

while I try to replace Double by string a new error appear

Could not cast value of type '__NSCFNumber' (0x1b7a0e0e0) to 'NSString' (0x1b7a1aad8). 2019-10-10 20:20:32.1 mapkitMap[1465:708355] Could not cast value of type '__NSCFNumber' (0x1b7a0e0e0) to 'NSString' (0x1b7a1aad8).

标签: swiftfirebasefirebase-realtime-database

解决方案


您似乎将您的一些latitudelongitude作为字符串值存储,

lat = String(location.latitude)
long = String(location.longitude)

所以你不能简单地从数据库中检索它们作为数字。您需要将它们作为字符串从数据库中读取,然后解析它们的数值。

就像是:

  let aSnap = snap as! DataSnapshot  
  let latitude = Double(snap.childSnapshot(forPath: "latitude").value)
  let longitude =  Double(snap.childSnapshot(forPath: "longitude").value)

推荐阅读