swift - 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).
解决方案
您似乎将您的一些latitude
和longitude
作为字符串值存储,
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)
推荐阅读
- javascript - 存储在变量中的 Array.prototype.slice.call 调用时会抛出错误
- php - Laravel PHPunit 测试返回 500
- c# - 如何在 C# 中将 WiFiPhyKind 映射到 Radio 类型
- javascript - 为什么即使数据没有存储在数据库中,我也会收到 200 响应?
- windows - 获取詹金斯奴隶失败
- nginx - nginx反向代理添加请求cookie
- perl - (perl) 终端 (Mac) 如何在 @INC 中找到 LWP...?
- awk - 如何减少文本文件中的所有数组索引?
- android - 如何将firebaseStorage中的图像路径获取到firebaseDatabase
- html - 当我使用不同的类时,我的字体真棒图标不起作用