【问题标题】:Type conversion error when reading data from Firebase从 Firebase 读取数据时出现类型转换错误
【发布时间】:2019-10-10 12:50:16
【问题描述】:

我正在使用 mapkit 制作应用程序,当我尝试从 firebase 获取用户位置时,这会导致这三行中的错误

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

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

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

我尝试用字符串替换双精度,但发生了新错误,然后我尝试用 AnyObject 替换它,它可以工作,但数据类似于 Optional(37.785834)。当我使用 AnyObject 数据做其他事情时,它总是会导致错误。

这是我的代码

@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)
        }
    }
}

这是我的错误

无法将“Swift._NSContiguousString”(0x1032681f8)类型的值转换为“NSNumber”(0x1b7a1abf0)。 2019-10-10 20:24:05。 mapkitMap[1468:709956] 无法将“Swift._NSContiguousString”(0x1032681f8)类型的值转换为“NSNumber”(0x1b7a1abf0)。 可选(37.785834)

当我尝试用字符串替换 Double 时,出现了一个新错误

无法将“__NSCFNumber”(0x1b7a0e0e0)类型的值转换为“NSString”(0x1b7a1aad8)。 2019-10-10 20:20:32.1 mapkitMap[1465:708355] 无法将类型“__NSCFNumber”(0x1b7a0e0e0)的值转换为“NSString”(0x1b7a1aad8)。

【问题讨论】:

  • 你能分享你的字典吗?
  • 我在下面写了一个快速答案,但后来意识到您的数据库中似乎混合了字符串和双精度数。您能否更新您的问题以包含导致问题的 JSON(作为文本,请不要截图)?您可以通过单击 Firebase Database console 的溢出菜单 (⠇) 中的“导出 JSON”链接来获取此信息。

标签: swift firebase firebase-realtime-database


【解决方案1】:

您似乎将您的一些 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)

【讨论】:

  • 谢谢,真的很有帮助,我检查了我的 JSON 并且发生了错误,因为更新的数据是 String,初始数据是 Double。我把它们都改成String类型后就可以了,谢谢。
猜你喜欢
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多